tags:

views:

200

answers:

1

I want to play back WAV sound (audio track of some custom video format) in Java, however, I have trouble using Clip for that: it seems only one instance is hearable at a time. Therefore, I switchet to the plain old SourceDataLine way.

In this context, I want to pause and resume the audio as the video is paused and unpaused. Unfortunately. When I call stop() on the SDL, the playback thread finishes entirely and the sound buffer is emptied:

sdl.open();
sdl.start();
sdl.write(dataBuffer);
sdl.drain();
sdl.stop();

Issuing an asynchronous stop() while the audio thread is blocking on write() or drain() will practically loose the playback position.

How can I pause with SourceDataLine in a blocking way, and/or how can I know how many audio has been played through it to do a resume using write(databuffer, skip, len)?

A: 

Hi,

You have not to stop(), but to stop sending your buffer (byte[]) to sdl.
I think your code has to look like this:

byte[] buffer = new byte[64]; // I use so a small buffer because the sound has to stop fast.
int bytesRead;
// ais is the AudioInputStream
while ((bytesRead = ais.read(buffer, 0, buffer.length)) != -1)
{
    sld.write(buffer, 0, bytesRead);
    while (paused)
    {
        try
        {
           Thread.sleep(1);
        } catch (Exception e) {}
    }
}

Hope this helps!

Martijn Courteaux
not really. This way, the data is only milliseconds away of the sound playback. Any thread slowdown and the sound becomes popping. Maybe I should do something with the return value of the write() call.
kd304