Java using mp3, ogg and wav files with javax.sound.sampled.Clip (or getting the bitrate of the sound file)

627 views Asked by At

My goal is to play multiple mp3, ogg, or wav music files at the same time in order to create adaptative music in a video game.

Instead of using the Clip class from the java sound API, I managed to create a class named Track which, thanks to mp3spi, and vorbisspi, can read mp3, ogg, and wav files by writing the audio data in a SourceDataLine. I found this solution thanks to this post:

https://stackoverflow.com/a/17737483/13326269

Everything works fine with a thread into the stream function so I can create many Track objects to play multiple sounds at the same time. But I want to create a function like void setMicrosecondPosition(long microseconds); from the Clip class.

I tried many things and I found a way to do it :

in = getAudioInputStream(new File(file).getAbsoluteFile());
int seconds = 410;
int bitrate = 320; //in kbit/s
in.skip(seconds*bitrate*1000/8); // divided by 8 because the skip method use bytes.

But I need the bitrate of the file. So, how can I get the bitrate of any sound file? Or better, how can I use mp3 and ogg files with the javax.sound.sampled.Clip class.

1

There are 1 answers

0
Phil Freihofner On

I believe if you really do have working AudioInputStreams, the skip function references a number of bytes which should be a fixed amount per frame, determined by the audio format. For example stereo, 16-bit would be 4 bytes per frame, regardless. So you should be able to use the frame rate (e.g., 44100 frames/sec) to skip to the desired start point.

Another dodge would be to read but ignore the bytes incoming from the AudioInputStream in a method similar to the stream method in your link solution's example. You this can pretty quickly get you to the desired point, since you won't be blocked by the sdl write(). But if that works, the skip method should also work and would be preferable.