I have compiled all of my sound effects into one sequenced .ogg file. I have the start and stop times for each sound effect. How do I play the individual effects? That is, how do I play part of an audio file.

More specificially, I've created a dictionary

        src: 'sfx.ogg',
        start: 265, // ms
        length: 212 // ms

that my play_sound() function can use to look up 'sword_hit' and play the correct audio file at the correct start time for the correct duration. I simply need to know how to tell the WebAudio API to start playing at start ms and only play for length ms.

  • \$\begingroup\$ Have you googled this topic yet? There's so much docs on the web on how to do this already. \$\endgroup\$ – XiaoChuan Yu Jun 23 '13 at 0:25
  • \$\begingroup\$ You don't understand my question. Or you didn't read it. \$\endgroup\$ – Matthew James Davis Jun 23 '13 at 10:28
  • 1
    \$\begingroup\$ Have you read the actual API and found the currentTime attribute yet? stackoverflow.com/questions/9563887/… \$\endgroup\$ – Patrick Hughes Jun 23 '13 at 17:43
  • \$\begingroup\$ I put an answer below, let me know if that helps. \$\endgroup\$ – XiaoChuan Yu Jun 24 '13 at 1:00

Read official docs on AudioBufferSourceNode. You can use start method's offset and duration parameters to play a sound in your sequenced file by setting offset where a particular sound effect starts in the file and duration to how long the effect is.


var context = new AudioContext();

function playSoundEffect(start, length) { //Ex. start=265, length = 212 
    var source = context.createBufferSource();
    source.buffer = sequencedSoundBuffer; //loaded from your sequenced.ogg file
    source.start(0, start/1000, length/1000); //Convert from ms to seconds
| improve this answer | |
  • \$\begingroup\$ Thank you so much! Sorry, I searched and searched for this, but couldn't find anything. Only stuff about playing whole audio files and applying filters. \$\endgroup\$ – Matthew James Davis Jun 24 '13 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.