How to play audio byte array (not file!) with JavaScript in a browser

后端 未结 4 2058
终归单人心
终归单人心 2021-02-08 14:51

For mostly security reasons, I\'m not allowed to store a WAV file on the server to be accessed by a browser. What I have is a byte array contains audio data (the data portion of

4条回答
  •  你的背包
    2021-02-08 15:32

    I accomplished this via the following code. I pass in a byte array containing the data from the wav file to the function playByteArray. My solution is similar to Peter Lee's, but I could not get his to work in my case (the output was garbled) whereas this solution works well for me. I verified that it works in Firefox and Chrome.

    window.onload = init;
    var context;    // Audio context
    var buf;        // Audio buffer
    
    function init() {
        if (!window.AudioContext) {
        if (!window.webkitAudioContext) {
            alert("Your browser does not support any AudioContext and cannot play back this audio.");
            return;
        }
            window.AudioContext = window.webkitAudioContext;
        }
    
        context = new AudioContext();
    }
    
    function playByteArray(byteArray) {
    
        var arrayBuffer = new ArrayBuffer(byteArray.length);
        var bufferView = new Uint8Array(arrayBuffer);
        for (i = 0; i < byteArray.length; i++) {
          bufferView[i] = byteArray[i];
        }
    
        context.decodeAudioData(arrayBuffer, function(buffer) {
            buf = buffer;
            play();
        });
    }
    
    // Play the loaded file
    function play() {
        // Create a source node from the buffer
        var source = context.createBufferSource();
        source.buffer = buf;
        // Connect to the final output node (the speakers)
        source.connect(context.destination);
        // Play immediately
        source.start(0);
    }
    

提交回复
热议问题