我需要录制和播放音频文件,我使用这两段代码:
录音:
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失败:状态= 0x80000000
有人遇到此问题吗?并知道我应该如何处理它?如果没有,我可以用来录制和播放音频文件吗?
答案 0 :(得分:2)
如果文件已损坏或处理的MediaPlayer服务未正确处理,则会发生这种情况。
参见一些例子:
MediaPlayer.setDataSource causes IOException for valid file
Exception when calling setDataSource(FileDescriptor) method (failed.: status=0x80000000)
此外,可能是录制后文件未正确关闭且播放器失败。
答案 1 :(得分:1)
尝试使用mpeg4 outputFormat
private void initRecorder() {
try {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mRecorder.setOutputFile(RECORD_FILE_NAME);
mRecorder.prepare();
mRecorder.start();
} catch (IllegalStateException | IOException e) {
Utility.e("initRecorder: " + e.getMessage());
}
}