您的位置:首页 > 其它

一个基于MedioRecorder的安卓录音软件【笔记】

2013-12-06 23:03 363 查看
先看效果图:







源代码:

package com.android.recordaudiodemo;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
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.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
*
* 一个基于MedioRecorder的录音软件
*
* @author Administrator
*
*/
public class MainActivity extends Activity implements OnClickListener,
OnItemClickListener, OnItemLongClickListener {

// 声明控件
private Button recordButton, stopButton;
private TextView textView, nameText;
private ListView listView;
private ImageView imageView;

// 声明MediaRecorder对象
private MediaRecorder mediaRecorder;
private File savePath; // 录音文件存储的文件路径
private ArrayList<HashMap<String, Object>> audioList = new ArrayList<HashMap<String, Object>>(); // 录音文件列表

private String recordFilePre = "record_"; // 录音文件前缀
private File recordFile; // 录音文件
private SimpleAdapter simpleAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

recordButton = (Button) findViewById(R.id.record);
stopButton = (Button) findViewById(R.id.stop);
textView = (TextView) findViewById(R.id.text);
listView = (ListView) findViewById(R.id.list);
imageView = (ImageView) findViewById(R.id.img);

// 点击按钮
recordButton.setOnClickListener(this);
stopButton.setOnClickListener(this);
// listView.setOnItemClickListener(this);
listView.setOnItemLongClickListener(this);

// 判断是否存在SD卡
boolean sdCardDir = Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
if (sdCardDir) {
// 设置录音文件的存储路径
savePath = Environment.getExternalStorageDirectory();
} else {
Toast.makeText(MainActivity.this, "没有找到SD卡", Toast.LENGTH_SHORT)
.show();
}
// 加载录音文件列表
getRecordList();
}

/* 创建录音文件列表 */
private void getRecordList() {
// TODO Auto-generated method stub
if (savePath.listFiles(new AudioFilter()).length > 0) {
for (int i = 0; i < savePath.listFiles(new AudioFilter()).length; i++) {
HashMap<String, Object> audioMap = new HashMap<String, Object>();
audioMap.put("name",
savePath.listFiles(new AudioFilter())[i].getName());
audioMap.put("size",
getLenght(savePath.listFiles(new AudioFilter())[i].length()));
audioList.add(audioMap);
}
}
// 适配器
simpleAdapter = new SimpleAdapter(MainActivity.this, audioList,
R.layout.item, new String[] { "name", "size" }, new int[] {
R.id.fileName, R.id.fileSize });
listView.setAdapter(simpleAdapter);
}

// 按钮点击事件
@Override
public void onClick(View v) {
// TODO Auto-generated method stub

switch (v.getId()) {
case R.id.record:
try {
if (mediaRecorder == null) {
textView.setText("Start recording...");
imageView.setImageResource(R.drawable.rec_bg2);
// 实例化MediaRecorder对象
mediaRecorder = new MediaRecorder();
// 创建录音文件
recordFile = File.createTempFile(recordFilePre, ".amr",
savePath);
// 设置麦克风
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
// 设置格式
mediaRecorder
.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
// 设置编码
mediaRecorder
.setAudioEncoder(MediaRecorder.VideoEncoder.DEFAULT);
// 设置输出路径
mediaRecorder.setOutputFile(recordFile.getAbsolutePath());
// 录音准备
mediaRecorder.prepare();
// 录音开始
mediaRecorder.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;

case R.id.stop:
// 停止录音
textView.setText("");
imageView.setImageResource(R.drawable.rec_bg1);
if (recordFile != null) {
mediaRecorder.stop();
// 将录音文件显示到列表
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", recordFile.getName());
map.put("size", getLenght(recordFile.length()));
audioList.add(map);
simpleAdapter = new SimpleAdapter(MainActivity.this, audioList,
R.layout.item, new String[] { "name", "size" },
new int[] { R.id.fileName, R.id.fileSize });
listView.setAdapter(simpleAdapter);

mediaRecorder.release();
mediaRecorder = null;
recordFile = null;
} else {
mediaRecorder = null;
}
break;
}
}

// 列表点击事件
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
nameText = (TextView) arg1.findViewById(R.id.fileName);
playAudio(new File(savePath + File.separator + nameText.getText()));
}

// 列表长按事件
@Override
public boolean onItemLongClick(AdapterView<?> arg0, final View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder aBuilder = new AlertDialog.Builder(this);
// aBuilder.setTitle("Prepar");
aBuilder.setItems(new String[] { "Play", "Delete", "Delete All" },
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
nameText = (TextView) arg1.findViewById(R.id.fileName);
if (which == 0) {
// 播放录音文件
// nameText = (TextView)
// arg1.findViewById(R.id.fileName);
// sizeText = (TextView)
// arg1.findViewById(R.id.fileSize);
playAudio(new File(savePath + File.separator
+ nameText.getText()));
} else if (which == 1) {
// 删除录音文件
for (int i = 0; i < audioList.size(); i++) {
if (nameText.getText().equals(
audioList.get(i).get("name"))) {
audioList.remove(i);
new File(savePath + File.separator
+ nameText.getText()).delete();
break;
}
}
listView.setAdapter(simpleAdapter);
} else if (which == 2) {
// 删除全部录音文件
for (int i = 0; i < audioList.size(); i++) {
new File(savePath + File.separator
+ audioList.get(i).get("name"))
.delete();
}
audioList.clear();
listView.setAdapter(simpleAdapter);
}
}
});
aBuilder.create().show();
return true;
}

/**
* 播放录音文件
*
* @param file
*/
@SuppressWarnings("static-access")
private void playAudio(File file) {
Intent intent = new Intent();
intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "audio");
startActivity(intent);

}

/**
* 获取文件 长度
*
* @param lenght
* @return
*/
public static String getLenght(long lenght) {
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
if (lenght >= 1073741824) {
return df.format((double) lenght / 1073741824) + "GB";
} else if (lenght >= 1048576) {
return df.format((double) lenght / 1048576) + "MB";
} else if (lenght >= 1024) {
return df.format((double) lenght / 1024) + "KB";
} else {
return df.format(lenght) + "B";
}
}

}

/**
* 创建音频文件类型过滤器
*
* @author Administrator
*
*/
class AudioFilter implements FilenameFilter {

@Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
return filename.endsWith(".amr");
}

}

需要注意的是:

1、layout有两个布局文件:activity_main.xml 和 item.xml;

2、AndroidManifest.xml文件需要设置权限:

<!-- SD卡写权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 录音权限 -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Demo源代码在这里:http://download.csdn.net/detail/bellovin/6671821
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息