开发者

Pause a SourceDataLine playback

开发者 https://www.devze.com 2022-12-08 19:20 出处:网络
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

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)?


The intended way is to call stop() on the SourceDataLine to pause it and start() to resume it. If you stop feeding the SourceDataLine with audio data when it's started, it will cause a buffer underrun which is generally regarded as an error condition. Only stop feeding data when it's in stopped state.

drain() should be called at the end when want to ensure that all data is played out that you've written into the SourceDataLine. Don't call it for "pause" functionality!

It is correct that you should write small buffers to the Source Data Line for better control. A good size is the equivalent of 50ms buffers -- use the open(AudioFormat, bufferSize) method to specify the buffer size in bytes (e.g. 8820 bytes for 44100Hz, 16-bit stereo).

Also I'd say that using a Clip is the preferred solution. Use start() and stop() on Clip and it should not swallow much. Most Java Sound implementations use a SourceDataLine internally for the Clip, so there should be no functional difference. Java Sound should make sure that you can play multiple Clip's at once.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号