0

I'm trying to calculate the exact song duration of an mp3 file in Android.

I tried using the calculation: song duration = filesize / bitrate, which produces extremely close results, but I'd like to calculate it more precisely.

I found a solution in Java here where it suggests this calculation: song duration = filesize / (framesize * framerate) and provides this example code:

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
AudioFormat format = audioInputStream.getFormat();
long audioFileLength = file.length();
int frameSize = format.getFrameSize();
float frameRate = format.getFrameRate();
float durationInSeconds = (audioFileLength / (frameSize * frameRate));

However, AudioInputStream is no longer supported in Android. So then I tried figuring out how to obtain the frame size and the frame rate with Android, but I can't find any solutions there either. Any ideas for how to calculate this in Android?

As an aside, using MediaMetadataRetriever.METADATA_KEY_DURATION as suggested here doesn't produce the correct song duration for me. The reason is because I'm streaming my mp3 file, and attempting to calculate the song duration strictly from the file's header information. That way, I can correctly update my progress bar very early on in the streaming process.

Community
  • 1
  • 1
Luke
  • 2,187
  • 1
  • 18
  • 29
  • `no longer`? AudioInputStream was never a part of android. You may want to look at MediaCodec and MediaFormat – njzk2 Nov 07 '14 at 20:01
  • What are you using to stream the mp3 files? I do with MediaPlayer and a MediaController the duration is correctly displayed for me. – Squonk Nov 07 '14 at 20:10
  • @Squonk, I'm streaming non-public mp3 files from Google Drive using the Google Drive Web Services API, so the standard MediaPlayer solution won't work for me. I think for it to work, I'd need a public URL. – Luke Nov 07 '14 at 20:16

0 Answers0