Android MediaRecorder实现录音机功能

1、需要一个File 和 MediaRecorder类

MediaRecorder  myMediaRecorder = new MediaRecorder();

myMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);                                         //   设置录音的数据源是麦克风

myMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);                             //  设置输出流的类型(默认)

myMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);                             // 设置录音的编码格式(默认)

myMediaRecorder.setOutputFile(mediaFile.getAbsolutePath());                                                           //  设置录音文件的保存路径

myMediaRecorder.prepare();                                                                                          //准备就绪

myMediaRecorder.start();                              //开始录音

2、录音结束后记得停止 释放资源

myMediaRecorder.stop();

myMediaRecorder.release();

myMediaRecorder = null;

3、记得加权限 使用麦克风和对SD卡写操作的权限

<uses-permission android:name="android.permission.RECORD_AUDIO"/>

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


源码如下:

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener,
		OnItemClickListener {

	private File mediaFile = null;
	private File mediaPath = null;
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");// 录音文件名采用日期形式
	private static final String MEDIA_UNMOUNTED_STRING = "没有可用SD卡,请插入SD卡重试!";
	private static final String READ_ONLY_STRING = "SD卡可读不可写,请检查!";
	private static final int MEDIA_UNMOUNTED = 1;
	private static final int READ_ONLY = 2;

	private Button buttonStart = null;
	private boolean isStart = false;
	private Button buttonStop = null;
	private ListView listView = null;

	private MediaRecorder mediaRecorder = null;

	private List<String> musicList = new ArrayList<String>();
	private ArrayAdapter adapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		buttonStart = (Button) findViewById(R.id.buttonStart);
		buttonStop = (Button) findViewById(R.id.buttonStop);

		listView = (ListView) findViewById(R.id.listView);
		buttonStart.setEnabled(true);
		buttonStop.setEnabled(false);

		switch (initFile()) {
		case MEDIA_UNMOUNTED:
			Toast.makeText(getApplicationContext(), MEDIA_UNMOUNTED_STRING,
					Toast.LENGTH_LONG).show();
			return;
		case READ_ONLY:
			Toast.makeText(getApplicationContext(), READ_ONLY_STRING,
					Toast.LENGTH_LONG).show();
			return;
		default:
			getMusicList();
			buttonStart.setOnClickListener(this);
			buttonStop.setOnClickListener(this);
			listView.setOnItemClickListener(this);
			break;
		}

	}

	@Override
	/**
	 * 列表点击事件
	 */
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (isStart)
			return;
		File playFile = new File(mediaPath + File.separator
				+ musicList.get(arg2).toString());
		play(playFile);
	}

	/**
	 * 调用系统播放器播放录音文件
	 * 
	 * @param file
	 */
	public void play(File file) {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file), "audio");
		startActivity(intent);
	}

	@Override
	/**
	 * 按钮点击事件
	 */
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.buttonStart:
			mediaRecorder = new MediaRecorder();//实例化一个MediaRecorder对象
			mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 声音来源为麦克风
			mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);// 设置输出流格式
			mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);// 设置编码格式
			String timeString = format.format(new Date(System
					.currentTimeMillis())) + ".amr";  // 保存的文件名为当前系统时间,后缀是.amr
			mediaFile = new File(mediaPath, timeString);
			mediaRecorder.setOutputFile(mediaFile.getAbsolutePath());// 设置输出位置
			try {
				mediaRecorder.prepare();
				mediaRecorder.start();
				isStart = true;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			buttonStart.setEnabled(false);
			buttonStop.setEnabled(true);
			break;
		case R.id.buttonStop:
			if (mediaRecorder == null)
				return;
			mediaRecorder.stop();
			musicList.add(mediaFile.getName());
			getMusicList();
			mediaRecorder.release();
			mediaRecorder = null;
			buttonStart.setEnabled(true);
			buttonStop.setEnabled(false);
			isStart = false;
			break;
		default:
			break;
		}
	}

	@SuppressWarnings("unchecked")
	/**
	 * 获取录音文件列表
	 */
	public void getMusicList() {
		File homeFile = mediaPath;
		if (homeFile == null) {
			homeFile = new File(Environment.getExternalStorageDirectory()
					.getAbsoluteFile() + File.separator + "MyRecorder");
			if (!homeFile.exists()) {
				homeFile.mkdir();
			}
			return;
		}
		if (homeFile.listFiles().length == 0)
			return;
		for (File file : homeFile.listFiles()) {
			if (musicList.contains(file.getName()))
				continue;
			musicList.add(file.getName());
		}
		adapter = new ArrayAdapter(getApplicationContext(),
				android.R.layout.simple_list_item_1, musicList);
		listView.setAdapter(adapter);
	}

	/**
	 * 文件初始化
	 * 
	 * @return
	 */
	public int initFile() {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) { // 判断SD卡的状态
			return MEDIA_UNMOUNTED;
		}
		File tempPathFile = Environment.getExternalStorageDirectory(); // 该文件为SD卡根路径
		mediaPath = new File(tempPathFile.getAbsoluteFile() + File.separator
				+ "MyRecorder"); // 在SD卡中指向自己的文件夹
		if (!mediaPath.canWrite()) { // 判断SD卡是否可写入
			return READ_ONLY;
		}
		if (!mediaPath.exists()) {
			mediaPath.mkdir(); // 创建文件夹
		}
		return 0;
	}

}

布局文件XML如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <Button
        android:id="@+id/buttonStart"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/buttonStart" />

    <Button
        android:id="@+id/buttonStop"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/buttonStop" />
    
     <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:background="#99CCFF"/>


</LinearLayout>

你可能感兴趣的:(android,audio)