Sim*_*mon 25 audio android duration audio-recording
我制作了一个录音机应用程序,我想在列表视图中显示录音的持续时间.我保存这样的录音:
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();
}
Run Code Online (Sandbox Code Playgroud)
如何获得此文件的持续时间(以秒为单位)?
提前致谢
---编辑我搞定了,我在MediaPlayer.setOnPreparedListener()方法中调用了MediaPlayer.getduration(),所以它返回0.
Jac*_*cky 69
MediaMetadataRetriever
这是一种轻量级且高效的方法.MediaPlayer
太重了,可能会在滚动,分页,列表等高性能环境中出现性能问题.
此外,Error (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);
Run Code Online (Sandbox Code Playgroud)
Ero*_*rol 22
尝试这个以毫秒为单位获取持续时间:
MediaPlayer mp = MediaPlayer.create(yourActivity, Uri.parse(pathofyourrecording));
int duration = mp.getDuration();
Run Code Online (Sandbox Code Playgroud)
或者测量从纳秒recorder.start()
到recorder.stop()
纳秒的时间:
long startTime = System.nanoTime();
// ... do recording ...
long estimatedTime = System.nanoTime() - startTime;
Run Code Online (Sandbox Code Playgroud)
Hit*_*ahu 16
最快捷的方法是通过MediaMetadataRetriever
.然而,有一个抓
如果您使用URI和上下文来设置数据源,则可能会遇到错误 https://code.google.com/p/android/issues/detail?id=35794
解决方案是使用文件的绝对路径来检索媒体文件的元数据.
以下是执行此操作的代码段
private static String getDuration(File file) {
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(file.getAbsolutePath());
String durationStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
return Utils.formateMilliSeccond(Long.parseLong(durationStr));
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用以下格式之一将毫秒转换为人类可读格式
/**
* Function to convert milliseconds time to
* Timer Format
* Hours:Minutes:Seconds
*/
public static String formateMilliSeccond(long milliseconds) {
String finalTimerString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours > 0) {
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return String.format("%02d Min, %02d Sec",
// TimeUnit.MILLISECONDS.toMinutes(milliseconds),
// TimeUnit.MILLISECONDS.toSeconds(milliseconds) -
// TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds)));
// return timer string
return finalTimerString;
}
Run Code Online (Sandbox Code Playgroud)
Awa*_*Kab 13
试试用
long totalDuration = mediaPlayer.getDuration(); // to get total duration in milliseconds
long currentDuration = mediaPlayer.getCurrentPosition(); // to Gets the current playback position in milliseconds
Run Code Online (Sandbox Code Playgroud)
分为1000转换为秒.
希望这能帮到你.
您可以添加此选项以可靠且安全地获取音频文件的持续时间。如果它不存在或有错误,您将返回 0。
myAudioFile.getMediaDuration(context)
/**
* If file is a Video or Audio file, return the duration of the content in ms
*/
fun File.getMediaDuration(context: Context): Long {
if (!exists()) return 0
val retriever = MediaMetadataRetriever()
return try {
retriever.setDataSource(context, uri)
val duration = retriever.extractMetadata(METADATA_KEY_DURATION)
retriever.release()
duration.toLongOrNull() ?: 0
} catch (exception: Exception) {
0
}
}
Run Code Online (Sandbox Code Playgroud)
如果您经常使用 String 或 Uri 文件,我建议您还添加这些有用的帮助程序
fun Uri.asFile(): File = File(toString())
fun String?.asUri(): Uri? {
try {
return Uri.parse(this)
} catch (e: Exception) {
Sentry.captureException(e)
}
return null
}
fun String.asFile() = File(this)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
48417 次 |
最近记录: |