确定音频文件的持续时间和格式

Kaa*_*rel 13 audio android

给定音频文件的路径(在SD卡上),以毫秒为单位确定音频长度的最佳方法是什么,以及文件格式(或Internet媒体类型)?

(在一段时间内,人们可以使用MediaPlayer' getDuration方法,但这似乎太慢/笨拙.)

Joh*_*n K 12

对于音频文件的长度:

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();
Run Code Online (Sandbox Code Playgroud)

检查MimeType:https://stackoverflow.com/a/8591230/3937699

  • getDuration()可以在{Prepared,Started,Paused,Stopped,PlaybackCompleted}之一的状态下调用,因此prepare()是强制性的. (2认同)

Nol*_*esh 5

我认为最简单的方法是:

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))
        );
Run Code Online (Sandbox Code Playgroud)


dbr*_*son 1

只是为您提供一个答案,但您可能可以通过文件扩展名确定媒体类型 - 我认为 MediaFile可能可以帮助您。至于持续时间,我相信 getDuration() 方法实际上是本机调用,所以我不知道您是否能够更快地完成它。