MP3: a way to get position in milliseconds for any given byte position?

允我心安 提交于 2019-11-30 22:19:10

It doesn't work like that. Even if your MP3 file is constant-bit-rate encoded, which byte position encodes which second in the stream is variable. (To be sure, VBR encoding makes it a lot more variable than CBR, but all the same.) The only way to reliably get this information is to actually decode the stream up to that point, which you probably don't want to do. This is why even professional players such as XMMS cannot reliably update the slider when you skip around.

An MP3 file or stream is a sequence of frames, where each frame consists of a mp3 header and a mp3 data part.

header and data part information are used to create a audio frame that "sounds like the original".

Therefore a position in the mp3 file or stream can't be converted to a timestamp in the resulting audio stream.

Bill Vouronikos

The "hardest" way is doing a loop. Inside the loop you call your play() or player.play() method and after that put your thread to sleep for just enough milis so as the song can finish without starting the next song over it, but you must estimate for example a song with 7mb size has aproximately duration of about 3 minutes so you must sleep your thread in this space. Your song length is given by Files.readAllBytes(Path path). Something like that:

//i put 5 for example lets say 5 songs//
//1000000 bytes is 1MB the same calculation is the same for the rest  length numbers//
for(int i=0; i<5; i++){
   play();
   if(length>1000000 && length<7500000){
     try{
        Thread.sleep(milis);
     }
     catch(Exception e){
        e.printStackTrace;
}

You must create a byte[]array=Files.readAllBytes(Path path) and then a variable int length=array.length so as for every song to take its length.This method that i show is not super good but with a little attension it works fine enough.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!