我制作了一个录音机应用程序,我想在列表视图中显示录音的持续时间.我保存这样的录音:
MediaRecorder recorder = new MediaRecorder();
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
folder = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Audio recordings");
String[] files = folder.list();
int number = files.length + 1;
String filename = "AudioSample" + number + ".mp3";
File output = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Audio recordings" + File.separator
+ filename);
FileOutputStream writer = new FileOutputStream(output);
FileDescriptor fd = writer.getFD();
recorder.setOutputFile(fd);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
e.printStackTrace();
}
如何获得此文件的持续时间(以秒为单位)?
提前致谢
– -编辑
我搞定了,我在MediaPlayer.setOnPreparedListener()方法中调用了MediaPlayer.getduration(),所以它返回0.
解决方法:
MediaMetadataRetriever是一种轻量级且高效的方法. MediaPlayer太重,可能会在滚动,分页,列表等高性能环境中出现性能问题.
此外,错误(100,0)可能发生在MediaPlayer上,因为它很重,有时需要一次又一次地重启.
Uri uri = Uri.parse(pathStr);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(AppContext.getAppContext(),uri);
String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
int millSecond = Integer.parseInt(durationStr);