13

Given a path (on the SD card) to an audio file, what is the best way of determining the length of the audio in milliseconds and the file format (or Internet media type)?

(For the duration one could use MediaPlayer's getDuration-method, but this seems too slow/clumsy.)

Kaarel
  • 10,554
  • 4
  • 56
  • 78
  • 2
    This problem is also discussed at: - http://stackoverflow.com/questions/4709883/ - http://stackoverflow.com/questions/3357484/ – Kaarel Jul 29 '12 at 22:41

3 Answers3

12

For the length of the audio file:

File yourFile;
MediaPlayer mp = new MediaPlayer();
FileInputStream fs;
FileDescriptor fd;
fs = new FileInputStream(yourFile);
fd = fs.getFD();
mp.setDataSource(fd);
mp.prepare(); 
int length = mp.getDuration();
mp.release();

Check this for MimeType: https://stackoverflow.com/a/8591230/3937699

Klatschen
  • 1,652
  • 19
  • 32
John K
  • 496
  • 3
  • 14
  • Thanks, I'm aware of this solution. I'm wondering if there is another way. – Kaarel Jan 30 '11 at 21:22
  • If you can get away with not calling prepare, it shouldn't be too inefficient. – John K Jan 31 '11 at 18:36
  • 2
    getDuration() can be called in a state that is one of {Prepared, Started, Paused, Stopped, PlaybackCompleted}, so prepare() is obligatory. – Kaarel Feb 01 '11 at 19:05
5

I think the easiest way is:

MediaPlayer mp = MediaPlayer.create(this, Uri.parse(uriOfFile);
int duration = mp.getDuration();
mp.release();
/*convert millis to appropriate time*/
return String.format("%d min, %d sec", 
            TimeUnit.MILLISECONDS.toMinutes(duration),
            TimeUnit.MILLISECONDS.toSeconds(duration) - 
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration))
        );
Nolesh
  • 6,848
  • 12
  • 75
  • 112
1

Just taking a stab at an answer for you, but you could probably determine the media type by the file extension - which I think MediaFile may be able to help you with. As for duration, I believe the getDuration() method is actually a native call, so I don't know if you will be able to do it much faster.

dbryson
  • 6,047
  • 2
  • 20
  • 20
  • Thanks, MediaFile is not part of the SDK though, see http://stackoverflow.com/questions/2726280/ – Kaarel Jan 27 '11 at 12:46