MediaRecorder录音
首先需要2个权限:
1.录音的权限:RECORD_AUDIO
2.读取SD卡的权限:WRITE_EXTERNAL_STORAGE
package com.example.mediarecoder;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import java.io.File;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
/*
首先需要获取录音的权限和读取SD卡的权限
RECORD_AUDIO 录音权限
WRITE_EXTERNAL_STORAGE SD卡权限
*/
// 设置全局变量recorder
MediaRecorder recorder;
File output;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 创建一个存储的绝对路劲(以系统时间作为文件名,以MP3作为文件的后缀面)
output = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+System.currentTimeMillis()+".mp3");
}
public void start(View view){
// 创建出MediaRecorder的实例
recorder = new MediaRecorder();
// 设置recorder的输入资源(来源于麦克风,一般可以使用默认DEFAULT)
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 输出格式必须要在编码格式之前设置
// 设置输出格式
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB);
// 设置编码的格式
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
// 设置输出文件的地址
recorder.setOutputFile(output.getAbsolutePath());
// 开始录音
try {
// 准备
recorder.prepare();
// 开始
recorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stop(View view){
// 停止
if (recorder != null) {
// 停止
recorder.stop();
// 释放
recorder.release();
recorder = null;
}
}
public void play(View view){
// 播放录音(创建一个MediaPlayer,把需要播放的文件传进去)
MediaPlayer mediaPlayer = MediaPlayer.create(this, Uri.fromFile(output));
// 开始播放
mediaPlayer.start();
}
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:onClick="start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始录音" />
<Button
android:onClick="stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止录音" />
<Button
android:onClick="play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="播放" />
</LinearLayout>