Matthew James Davis
Matthew James Davis

Reputation: 12295

Playing parts of an audio file in WebAudio

Instead of loading 9 different audio files with a distinct sound effect, I have compiled my sound effects into one .ogg file and I have the various start and stop times for each effect. However, I don't see any way to handle this in the WebAudio API. I'm sure there is. Anyone know?

Upvotes: 0

Views: 221

Answers (1)

Matthew James Davis
Matthew James Davis

Reputation: 12295

Here's how to do it.

var context = new AudioContext();
var mainNode = context.createGainNode(0);
mainNode.connect(context.destination);

function play_sound(sound, start, length) { 
    var source = context.createBufferSource();
    source.buffer = get_buffer(sound); // assume get_buffer gets a file that has already been
    source.connect(mainNode);          // loaded and decoded with context.decodeAudioData()
    source.start(0, start, length);
}

// lets say I want to play a 0.2 second sound effect in sfx.ogg starting at 0.5 seconds.
play_sound('sfx.ogg', 0.5, 0.2);

Upvotes: 2

Related Questions