2011-01-26 175 views
13

給定音頻文件的路徑(在SD卡上),確定音頻長度(毫秒)和文件格式(或Internet媒體類型)的最佳方式是什麼? ?確定音頻文件的持續時間和格式

(在這段時間裏人們可以使用MediaPlayergetDuration - 方法,但這似乎過於緩慢/笨拙。)

+2

這個問題也是在討論: - http://stackoverflow.com/questions/4709883/ - http://stackoverflow.com/questions/3357484/ – Kaarel

回答

1

只是走一個刺在你的答案,但你很可能被確定媒體類型文件擴展名 - 我認爲MediaFile 可能能夠幫助你。至於持續時間,我相信getDuration()方法實際上是一個本地調用,所以我不知道你是否能夠做得更快。

+0

謝謝,雖然MediaFile不是SDK的一部分,請參閱http://stackoverflow.com/questions/2726280/ – Kaarel

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(); 

檢查此爲Mime類型: https://stackoverflow.com/a/8591230/3937699

+0

謝謝,我知道這個解決方案。我想知道是否有另一種方式。 – Kaarel

+0

如果您可以避免不打電話準備,它不應該太低效。 –

+2

getDuration()可以在{Prepared,Started,Paused,Stopped,PlaybackCompleted}之一的狀態中調用,所以prepare()是強制性的。 – Kaarel

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)) 
     ); 
相關問題