-1

I am trying to play a wav file using AudioContext - it plays correctly when loaded with <audio> tag (as shown in jsfiddle), but plays incorrectly when using AudioContext.

var startButton = document.getElementById('start-stream');
var wav = new wavefile.WaveFile();
startButton.onclick = function() {
  audioCtx = new AudioContext();
  wav.fromBase64(mydata);

  buffer = audioCtx.createBuffer(1, audioCtx.sampleRate * 3, audioCtx.sampleRate);

  // add audio data to buffer
  buffer.getChannelData(0).set(wav.getSamples());

  source = audioCtx.createBufferSource();
  source.buffer = buffer;
  source.connect(audioCtx.destination);
  source.start();
};

Fiddle is here: https://jsfiddle.net/Persiancoffee/6v8dLt3f/7/

Moe
  • 61
  • 4

1 Answers1

1

The decodeAudioData() function of the Web Audio API can decode WAV files which is why you don't need any external libraries for this use case. It will produce an AudioBuffer for you.

startButton.onclick = async function () {
    audioCtx = new AudioContext();

    const arrayBuffer = Uint8Array.from(
        atob(mydata),
        (character) => character.charCodeAt(0)
    ).buffer;

    buffer = await audioCtx.decodeAudioData(arrayBuffer);
    
    source = audioCtx.createBufferSource();
    source.buffer = buffer;
    source.connect(audioCtx.destination);
    source.start();
};

Here is a link to an updated version of your fiddle: https://jsfiddle.net/pzx0vg89/.

chrisguttandin
  • 7,025
  • 15
  • 21