Audio data streaming in HTML5

后端 未结 2 2067
误落风尘
误落风尘 2020-12-04 17:20

I am receiving PCM audio data from the server in small chunks and having them stored in an Array. Now I would like to play these audio chunks sequentially without gaps using

2条回答
  •  时光说笑
    2020-12-04 17:44

    Scheduling audio is something the Web Audio API was designed for. If you have the decoded PCM audio chunks as typed arrays (AUDIO_CHUNKS), you can create audio buffers for each chunk, and schedule them at an exact time (one after the other) using noteOn(). Something like:

    var startTime = 0;
    
    for (var i = 0, audioChunk; audioChunk = AUDIO_CHUNKS[i]; ++i) {
      // Create/set audio buffer for each chunk
      var audioBuffer = audioCtx.createBuffer(NUM_CHANNELS, NUM_SAMPLES, SAMPLE_RATE);
      audioBuffer.getChannelData(0).set(audioChunk);
    
      var source = audioCtx.createBufferSource();
      source.buffer = audioBuffer;
      source.noteOn(startTime);
      source.connect(audioCtx.destination);
    
      startTime += audioBuffer.duration;
    }
    

提交回复
热议问题