简体   繁体   English

使用HTML5播放流中的音频

[英]Playing audio from stream with HTML5

I've got problem with playing audio from stream in web browser. 我在网络浏览器中播放流音频有问题。 I am streaming voice via BinaryJS as 2048-length Int16 arrays to client's browser and I am getting very noisy output. 我通过BinaryJS将语音作为2048长度的Int16数组流式传输到客户端的浏览器,并且输出的声音非常嘈杂。 This is how I am receiving the stream: 这就是我接收流的方式:

 var 
    client,
    audioContext,
    audioBuffer,
    sourceNode,
    sampleSize = 2048,

  function main() {
    try {
        audioContext = new AudioContext();
    } catch(e) {
        alert('Web Audio API is not supported in this browser');
    }
    sourceNode = audioContext.createBufferSource();
    sourceNode.connect(audioContext.destination);

    connectClient();

    playSound();
  };

  function playSound() {

    sourceNode.start(0);    

  };

   function onError(e) {
    console.log('error' + e);
  };

  function connectClient() {
    client = new BinaryClient('ws://localhost:3000');
    client.on('open', function() {
      console.log('stream opened');

    });
    client.on('stream', function(stream, meta){
      stream.on('data', function(data){
        var integers = new Int16Array(data);
        var audioBuffer = audioContext.createBuffer(1, 2048, 4410);
        audioBuffer.getChannelData(0).set(integers);
        sourceNode.buffer = audioBuffer;
        });
      });
    };

  main();

What should I do to get clean audio? 我应该怎么做才能获得干净的音频?

I think your playback technique here is causing the noise – first of all, can you ensure that your stream event fires often enough to provide continuous data for Web Audio? 我认为您的播放技术正在引起噪音–首先,您是否可以确保stream事件触发频率足以为Web Audio提供连续数据? If it doesn't, then the noise you hear is the pops and clicks after each bit of audio stops playing. 如果不是,那么您听到的声音会在音频的每一比特停止播放后发出咔嗒声。 Also, updating the data by swapping ArrayBuffers on sourceNode isn't a good idea. 同样,通过交换sourceNode上的ArrayBuffers更新数据sourceNode是一个好主意。

I would suggest using a ScriptProcessorNode with your desired buffer size – this gives you the ability to insert raw data into the graph at audio rate, which should reduce the noise. 我建议您使用具有所需缓冲区大小的ScriptProcessorNode-这使您能够以音频速率将原始数据插入到图形中,这样可以减少噪声。 Look at this demo to see how to set up the node, basically you just need to fill the outputBuffer with your stream data. 查看此演示以了解如何设置节点,基本上,您只需要用流数据填充outputBuffer

This will only really help if your streaming is faster than the audio rate! 仅当您的流媒体速度快于音频速率时,这才真正有用!

Good luck, 祝好运,

jakub 的Jakub

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

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