Save audio to localStorage for playback

I am trying to create a function in which an mp3 file is pulled from

<input type="file" id="sound" accept="audio/*"/>

and stored in localStorage in Chrome. (I know that localStorage is limited in size, but the audio files that I will work with will be under 2 MB.) Once this audio file is saved, it will play using:

var audio = new Audio('audioFile');
audio.play();

I'm still new to web development, so any pointers would be great!

NOTE. This is not a duplicate of HTML5 audio recordings in a file . I am trying to take an existing mp3 file from my hard drive and save it to localStorage so that it can be played.

+4
source share
3

, . localStorage .

, :

, Base64 33%. , , , 64- , ASCII.

,

  • Base64 localStorage
  • Base64 ArrayBuffer
  • ArrayBuffer Audio
  • Audio <audio>

, localStorage 5-10 , . , , , mp3 , , , , , , - , .

+2

localStorage . IndexedDB API, .

DB Mozilla localForage, , localStorage.

Fiddle , StackSnippets® DB localStorage. >


( Blob) String, API localStorage, FileReader readAsDataURL(), dataURI, MediaElements.

f.onchange = e =>{
  if(f.files[0].type.indexOf('audio/') !== 0){
    console.warn('not an audio file');
    return;
    }
  const reader = new FileReader();
  reader.onload = function(){
    var str = this.result;
    // this is a string, so you can store it in localStorage, even if it really not a good idea
    console.log(str);
    const aud = new Audio(str);
    aud.play();
    };
  reader.readAsDataURL(f.files[0]);
  }
<input type="file" id="f">
Hide result
+6

indexedDB. bufferArray. bufferArray, , slice, .

-1

Source: https://habr.com/ru/post/1676527/


All Articles