_Before using MediaRecorder, AudioRecord was used to record audio and found that the more complex and recorded audio was all harsh.It is possible that the file also needs a header.If you want to record, use MediaRecorder, it's easy to use.
_Recording requires privileges, android 6.0 and above require runtime privileges.
<uses-permission android:name="android.permission.RECORD_AUDIO"
Sound recording
MediaRecorder mediaRecorder = new MediaRecorder();
//source
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//Output Format
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
//Set Encoding
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
File file = new File(getExternalCacheDir().getAbsolutePath(), "a.mp3");
//Location of file output
mediaRecorder.setOutputFile(file.getAbsolutePath());
mediaRecorder.prepare();
//Start recording
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
//Stop recording
mediaRecorder.stop();
//release
mediaRecorder.release();
play
- MediaPlayer
File file = new File(getExternalCacheDir().getAbsolutePath(), "a.mp3");
MediaPlayer mediaPlayer = new MediaPlayer();
try {
//Audio file address
mediaPlayer.setDataSource(file.getAbsolutePath());
mediaPlayer.prepare();
//play
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
- SoundPool
_SoundPool can play multiple audio files at the same time.
SoundPool soundPool = new SoundPool.Builder()
.setMaxStreams(maxStreams) //Set maximum concurrency value
.build();
//Load Resources
int t = soundPool.load(this, R.raw.a, 0);
//Parameter 1: Audio id
//Parameter 2: Left channel 0.0-1.0
//Parameter 3: Right channel 0.0-1.0
//Parameter 4: Priority
//Parameter 5: Play times, -1 bit cycle
//Parameter 6: Play rate, 1 is normal, 0.5-2.0
soundPool.play(t, 1, 1, 0, 0, (float) 2.0);