dpq
dpq

Reputation: 9268

Low-latency audio streaming in Flash

Suppose there is a live WAV stream that can be reached at a certain URL, and we need to stream it with as little latency as possible. Using HTML5 <audio> for this task is a no-go, because browsers attempt to pre-buffer several seconds of the stream, and the latency goes up accordingly. That's the reason behind using Flash for this task. However, due to my inexperience with this technology, I only managed to get occasional clicks and white noise. What's wrong in the code below? Thanks.

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);
    }
}

Upvotes: 1

Views: 802

Answers (1)

Sean Fujiwara
Sean Fujiwara

Reputation: 4546

Like The_asMan pointed out, playing a wav file is not that easy. See as3wavsound for an example.

If your goal is low latency, the best option would be to convert to MP3, so you can use just use a SoundLoaderContext.

Upvotes: 1

Related Questions