简体   繁体   中英

Loading mp3 as ArrayBuffer using local file for Web Audio

i wish load a mp3 local file and next using a library for processing, i cant use XMLHttpRequest, then i use the next code for read a local mp3 file:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body onload="carga();">
        <input id="audio_file" type="file" accept="audio/*" />
        <audio id="audio_player" />
        <script>
            function carga() {

                audio_file.onchange = function(){
                var files = this.files;
                console.log(files);
                alert(files);
                var file = URL.createObjectURL(files[0]); 
                console.log(file);
                alert(file);
                audio_player.src = file; 
                audio_player.play();
                                                };
            }
        </script>
    </body>
</html>

but XMLHttpRequest return ArrayBuffer, and my code return a FileList, i need a ArrayBuffer for my next processing, how i can load a local mp3 file as a ArrayBuffer?

On modern Browser you can use a FileReader and its method readAsArrayBuffer .

  document.querySelector('input').onchange = function(){ var fileReader = new FileReader; fileReader.onload = function(){ var arrayBuffer = this.result; snippet.log(arrayBuffer); snippet.log(arrayBuffer.byteLength); } fileReader.readAsArrayBuffer(this.files[0]); var url = URL.createObjectURL(this.files[0]); audio_player.src = url; audio_player.play(); }; 
 <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> <input id="audio_file" type="file" accept="audio/*" /> <audio id="audio_player" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM