在没有使用MediaRecorder之前,使用AudioRecord来录制音频,发现比较复杂而且录制出来的音频全都是很刺耳的声音。有可能文件还需要文件头。如果要录音,使用MediaRecorder就好了,使用简单明了。
录音所需要的权限,android 6.0及以上系统需要使用运行时权限。
<uses-permission android:name="android.permission.RECORD_AUDIO"
录音
MediaRecorder mediaRecorder = new MediaRecorder();
//来源
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//输出格式
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
//设置编码
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
File file = new File(getExternalCacheDir().getAbsolutePath(), "a.mp3");
//文件输出的位置
mediaRecorder.setOutputFile(file.getAbsolutePath());
mediaRecorder.prepare();
//开始录音
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
//停止录音
mediaRecorder.stop();
//释放
mediaRecorder.release();
播放
- MediaPlayer
File file = new File(getExternalCacheDir().getAbsolutePath(), "a.mp3");
MediaPlayer mediaPlayer = new MediaPlayer();
try {
//音频文件地址
mediaPlayer.setDataSource(file.getAbsolutePath());
mediaPlayer.prepare();
//播放
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
- SoundPool
SoundPool能够同时播放多个音频文件。
SoundPool soundPool = new SoundPool.Builder()
.setMaxStreams(maxStreams) //设置最大并发值
.build();
//装载资源
int t = soundPool.load(this, R.raw.a, 0);
//参数一:音频id
//参数二:左声道0.0-1.0
//参数三:右声道0.0-1.0
//参数四:优先级
//参数五:播放次数,-1位循环
//参数六:播放速率,1为正常, 0.5-2.0
soundPool.play(t, 1, 1, 0, 0, (float) 2.0);