How do I tell a AudioBufferSourceNode to start and end in the middle of a buffer?

html, javascript, web-audio-api

Solution

Just use the additional (optional) parameters to `AudioBufferSourceNode#start`

// begin playback immediately, starting at second 10 of the buffer 
// and lasting 20 seconds
sourceNode.start( audioContext.currentTime, 10, 20 );

First parameter is `when`, which you're probably familiar with. This just determines when the sound will start playing, using the coordinate system of `AudioContext#currentTime`.

Second parameter is `offset`. This is the number of seconds into your `AudioBuffer` instance. So if you want to start playback at 10 seconds into the buffer, you'd pass `10` here.

Third parameter is `duration`. Also in seconds, and hopefully pretty self explanatory. In case it's not, this determines how long the sound will play for.

Problem

I'm using the HTML5 audio app to incorporate sounds into my game. How do I create a AudioBufferSourceNode that starts and stops playing in the middle of an AudioBuffer? I found nothing in the AudioBufferSourceNode interface for creating an AudioBufferSourceNode that begins in the middle of a buffer: https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html#AudioBufferSourceNode I suppose I could create the AudioBufferSourceNode with a slice of the original AudioBuffer, but I want to conserve memory since my game already uses up a lot of javascript heap memory, so I really don't want to duplicate AudioBuffers or create portions thereof. I just want to make several AudioBufferSourceNodes that each play portions of a single AudioBuffer. How I do that?

Original source