ImJustACowLol
ImJustACowLol

Reputation: 951

(MP3) How To Calculate Byte Position In Java

How does one calculate the amount of bytes to skip with the InputStream.skip() method if you want to start the InputStream of a .mp3 file at a certain position in time?

I have access to the following data: The point that you want to start at in seconds

I have tried searching for a formula/algorithm that describes how to calculate it but I could not find it. Do any of you know how to do this?

-Edit

I tried doing framesize * framerate * position(seconds) but that was off by a factor 10. Dividing it by 10 still had it off by 3 seconds when skipped to 50 seconds in the song, even more when skipping larger chunks.

Upvotes: 0

Views: 597

Answers (1)

Ehsan Enayati
Ehsan Enayati

Reputation: 309

I am doing the same calculation in C++. In case a googler reaches this page, here is how I do it. So far it works fine. I assume the User wants to jump to time skipToTime (in seconds):

int numberOfFrames = (skipToTime * sampleRate)/1152;
int skipPositionInBytes = (numberOfFrames * frameSize);

One point is that the frameSize is not always the same. Specially, first and second frames might have different sizes than others. So it is better to measure them separately.

I assume the first two frames had different sizes and you calculated them, then the whole calculation will look like this:

int numberOfFrames = (skipToTime * sampleRate)/1152;
numberOfFrames -= 2; // Or whatever it took to reach a stable frame size
int skipPositionInBytes = (numberOfFrames * frameSize) + OFFSET;

OFFSET is the total number of bytes it took to reach a stable frame size. If it took 2 frames then:

OFFSET = frameSize1 + frameSize2;

Upvotes: 1

Related Questions