Flash中的低延迟音频流

时间:2012-03-06 18:34:33

标签: actionscript-3 flash audio-streaming

假设有一个可以在某个URL上访问的实时WAV流,我们需要以尽可能小的延迟流式传输它。使用HTML5 <audio>执行此任务是不行的,因为浏览器会尝试预缓冲数秒的流,并且延迟会相应增加。这就是使用Flash完成此任务的原因。但是,由于我对这项技术缺乏经验,我只能偶尔获得点击和白噪声。下面的代码有什么问题?感谢。

var soundBuffer: ByteArray = new ByteArray();
var soundStream: URLStream = new URLStream();
soundStream.addEventListener(ProgressEvent.PROGRESS, readSound);
soundStream.load(new URLRequest(WAV_FILE_URL));
var sound = new Sound();
sound.addEventListener(SampleDataEvent.SAMPLE_DATA,playSound);
sound.play();

function readSound(event:ProgressEvent):void {
    soundStream.readBytes(soundBuffer, 0, soundStream.bytesAvailable);
}


function playSound(event:SampleDataEvent):void {
    /* The docs say that if we send too few samples,
      Sound will consider it an EOF */
    var samples:int = (soundBuffer.length - soundBuffer.position) / 4
    var toadd:int = 4096 - samples;
    try {
      for (var c: int=0; c < samples; c++) {
        var n:Number = soundBuffer.readFloat();
        event.data.writeFloat(n);
        event.data.writeFloat(n);
      }
    } catch(e:Error) {
        ExternalInterface.call("errorReport", e.message);
    }
    for (var d: int = 0; d < toadd; d++) {
        event.data.writeFloat(0);
        event.data.writeFloat(0);
    }
}

1 个答案:

答案 0 :(得分:1)

就像The_asMan指出的那样,播放一个wav文件并不容易。有关示例,请参阅as3wavsound

如果您的目标是低延迟,最好的选择是转换为MP3,这样您就可以只使用use a SoundLoaderContext