简体   繁体   English

播放正在生成的PCM

[英]Play PCM as it is being generated

I am generating some raw audio data in javascript and I need to play it as I am generating it. 我正在使用javascript生成一些原始音频数据,因此我需要在播放它时对其进行播放。 I searched for this here and the closest thing to what I am looking for is this . 我在这里搜索了这个,与我正在寻找的最接近的东西是这个 However, in the answer given there the array of data points is generated first and then the audio is played. 但是,在给出的答案中,首先生成数据点的数组,然后播放音频。 I need to play it while generating it. 我需要在生成它的同时进行播放。 Basically I am receiving some stream of some other data, processing it and generating the audio based on that. 基本上,我正在接收一些其他数据流,对其进行处理并基于该数据生成音频。 I need to play the audio corresponding to the data I am receiving as I am receiving it. 我需要在接收数据时播放与接收的数据相对应的音频。 (A simplified example is receiving the audio volume and frequency.) (一个简化的示例是接收音频音量和频率。)

If I'm getting the request correctly, then all you need is a ScriptProcessorNode . 如果我正确地收到了请求,那么您只需要一个ScriptProcessorNode即可
You will feed it with your PCM data in the following way: 您将通过以下方式将其与PCM数据一起输入:

  • wait for its onaudioprocess event. 等待其onaudioprocess事件。
  • get the outputBuffer from the event which is an AudioBuffer . 从事件获取outputBuffer,它是AudioBuffer
  • loop through each channels of the outputBuffer (will return an Float32Array). 循环遍历outputBuffer的每个通道(将返回Float32Array)。
  • loop through all the samples of the outputBuffer's channels data. 循环遍历outputBuffer的通道数据的所有样本。
  • set your own data 设置自己的数据

 function makeSomeNoise() { var ctx = new AudioContext(); var processor = ctx.createScriptProcessor(4096, 1, 1); processor.onaudioprocess = function(evt) { var outputBuffer = evt.outputBuffer; // Loop through the output channels for (var channel = 0; channel < outputBuffer.numberOfChannels; channel++) { var outputData = outputBuffer.getChannelData(channel); // Loop through the 4096 samples for (var sample = 0; sample < outputBuffer.length; sample++) { outputData[sample] = ((Math.random() * 2) - 1) * 0.5; } } }; processor.connect(ctx.destination); } btn.onclick = function() { if (confirm("That won't be really nice")) makeSomeNoise(); } 
 <button id="btn">make some noise</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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