title: Android Calculate MP3 Song Duration From Frame Size and Frame Rate
body: <p>I'm trying to calculate the exact song duration of an mp3 file in Android.</p>
  
  <p>I tried using the calculation: song duration = filesize / bitrate, which produces extremely close results, but I'd like to calculate it more precisely.</p>
  
  <p>I found a solution in Java <a href="https://stackoverflow.com/questions/3009908/how-do-i-get-a-sound-files-total-time-in-java">here</a> where it suggests this calculation: song duration = filesize / (framesize * framerate) and provides this example code:</p>
  
  <pre><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));
  </code></pre>
  
  <p>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?</p>
  
  <p>As an aside, using MediaMetadataRetriever.METADATA_KEY_DURATION as suggested <a href="https://stackoverflow.com/questions/9834697/how-to-get-the-duration-of-an-mp3-file-in-android">here</a> 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.</p>