我需要录制和播放音频文件,我使用这两段代码:
用于录制:
private void initRecorder() {
try {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mRecorder.setOutputFile(RECORD_FILE_NAME);
mRecorder.prepare();
mRecorder.start();
} catch (IllegalStateException | IOException e) {
Utility.e("initRecorder: " + e.getMessage());
}
}
对于玩:
try {
FileDescriptor fd = null;
FileInputStream fis = new FileInputStream(RECORD_FILE_NAME);
fd = fis.getFD();
if (fd != null) {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(fd);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mPlayTime > 0) {
mMediaPlayer.seekTo(mPlayTime);
}
mMediaPlayer.start();
setStatus(STATUS_PLAYING);
}
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mMediaPlayer.release();
RecordMomentActivity.this.mPlayTime = 0;
setStatus(STATUS_NOT_PLAYING);
}
});
}
} catch (Exception e) {
Utility.e("Exception: " + e.getMessage());
setStatus(STATUS_NOT_PLAYING);
}
}
此代码在Nexus 5(Android 6.0)和LG G3与Android 5.0上运行良好,录制和播放音频.但是当我使用三星手机时,我得到了例外:
setDataSourceFD failed.: status=0x80000000
有人遇到这个问题吗?并知道我应该如何处理它?如果没有,我可以用来录制和播放音频文件吗?
解决方法:
如果文件已损坏或处理的MediaPlayer服务未正确处理,则会发生这种情况.
看一些例子:
MediaPlayer.setDataSource causes IOException for valid file
Exception when calling setDataSource(FileDescriptor) method (failed.: status=0x80000000)
此外,可能是录制后文件未正确关闭且播放器出现故障.