Reputation: 10672
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.)
Upvotes: 13
Views: 10515
Reputation: 506
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
Upvotes: 12
Reputation: 7018
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))
);
Upvotes: 5
Reputation: 6127
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.
Upvotes: 1