录制mp3的过程中,主要是将数据写入到文件中,其中一段关键的方法是setOutputFile,设置数据输出的文件,如果文件不存在的话,则无法进行录制的效果
1、创建文件,用于将数据写入,如果不存在数据的话无法进行录音
private String mp3Path = getDiskCachePath(EasyApplication.getEasyApplication()) +"/mp4-pcm" + "/" + "sign.mp3";
File mp3File = new File(mp3Path);
if (!mp3File.exists()) {
try (FileOutputStream fos = new FileOutputStream(mp3File)) {
Log.d(TAG, "initView: " + fos);
} catch (IOException e) {
e.printStackTrace();
}
}
2、录音工作的准备
private void prepareRecord(){
File mp3File = new File(mp3Path);
Log.d(TAG, "prepareRecord: " + mp3File.getAbsolutePath());
if (mp3File.exists()){
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setAudioEncodingBitRate(96000);
recorder.setAudioSamplingRate(44100);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
recorder.setOutputFile(mp3File);
}
} catch (IllegalStateException e) {
Log.e(TAG, "initView: ", e );
e.printStackTrace();
}
}else {
if (!mp3File.exists()) {
Toast.makeText(getActivity(),"",Toast.LENGTH_SHORT).show();
try (FileOutputStream fos = new FileOutputStream(mp3File)) {
Log.d(TAG, "initView: " + fos);
} catch (IOException e) {
e.printStackTrace();
}
}
Log.d(TAG, "prepareRecord: " + mp3File.getAbsolutePath());
}
}
3、开始进行录音
private void startReading() {
if (recorder != null){
mOnReading = true;
try {
recorder.prepare();
recorder.start();
} catch (IOException e) {
Log.e(TAG, "startReading: ", e );
}
}else {
prepareRecord();
}
}
4、停止录音
private void stopReading() {
mOnReading = false;
if (recorder != null){
recorder.stop();
recorder.release();
recorder = null;
}