Android获取mp3音频文件播放总时长

Android获取mp3音频文件播放总时长

一般是需要文件的绝对路径,需要读取文件,转成媒体类解析,最好获取播放时长,然后关闭资源。
/**
* 获取音频文件的总时长大小
*
* @param filePath 音频文件路径
* @return 返回时长大小
*/
public long getAudioFileVoiceTime(String filePath) {
long mediaPlayerDuration = 0L;
if (filePath == null || filePath.isEmpty()) {
return 0;
}
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayerDuration = mediaPlayer.getDuration();
} catch (IOException ioException) {
LogUtil.i(TAG, ioException.getMessage());
}
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
return mediaPlayerDuration;
}
还有就是资源文件,读取方式不一样,后面的流程是一样的
/**
* 获取音频文件的总时长大小
*
* @param rawId raw资源文件ID
* @return 返回时长大小
*/
public long getRawFileVoiceTime(int rawId) {
long mediaPlayerDuration = 0L;
MediaPlayer mediaPlayer = new MediaPlayer();
try {
Uri uri = Uri.parse("android.resource://"+getContext().getPackageName()+"/"+ rawId);
mediaPlayer.setDataSource(BaseApplication.getContext(), uri);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepare();
mediaPlayerDuration = mediaPlayer.getDuration();
} catch (Exception exception) {
LogUtil.i(TAG, exception.getMessage());
}
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
return mediaPlayerDuration;
}

你可能感兴趣的:(android,android,android,studio,播放总时长)