Android : 录音实现之AudioRecord类
Author : Aoyousatuo Zhao
http://blog.sina.com.cn/aoyousatuo
Android系统提供了一些类以便应用去实现录音的功能。AndioRecord就是其中一个。那么我们如何通过AudioRecord去实现录音呢?笔者下面就给大家做一个介绍。
首先看看Android帮助文档中对该类的简单概述: AndioRecord类的主要功能是让各种JAVA应用能够管理音频资源,以便它们通过此类能够录制平台的声音输入硬件所收集的声音。此功能的实现就是通过”pulling同步”(reading读取)AudioRecord对象的声音数据来完成的。在录音过程中,应用所需要做的就是通过后面三个类方法中的一个去及时地获取AudioRecord对象的录音数据. AudioRecord类提供的三个获取声音数据的方法分别是read(byte[], int, int), read(short[], int, int), read(ByteBuffer, int). 无论选择使用那一个方法都必须事先设定方便用户的声音数据的存储格式。
开始录音的时候,一个AudioRecord需要初始化一个相关联的声音buffer,这个buffer主要是用来保存新的声音数据。这个buffer的大小,我们可以在对象构造期间去指定。它表明一个AudioRecord对象还没有被读取(同步)声音数据前能录多长的音(即一次可以录制的声音容量)。声音数据从音频硬件中被读出,数据大小不超过整个录音数据的大小(可以分多次读出),即每次读取初始化buffer容量的数据。
一般情况下录音实现的简单流程如下:
1. 创建一个数据流。
2. 构造一个AudioRecord对象,其中需要的最小录音缓存buffer大小可以通过getMinBufferSize方法得到。如果buffer容量过小,将导致对象构造的失败。
3. 初始化一个buffer,该buffer大于等于AudioRecord对象用于写声音数据的buffer大小。
4. 开始录音。
5. 从AudioRecord中读取声音数据到初始化buffer,将buffer中数据导入数据流。
6. 停止录音。
7. 关闭数据流。
程序示例 :
1. JAVA
public class myAudioRecorder extends Activity {
private boolean isRecording = false ;
private Object tmp = new Object() ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button)findViewById(R.id.start_bt) ;
start.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Thread thread = new Thread(new Runnable() {
public void run() {
record();
}
});
thread.start();
findViewById(R.id.start_bt).setEnabled(false) ;
findViewById(R.id.end_bt).setEnabled(true) ;
}
}) ;
Button play = (Button)findViewById(R.id.play_bt) ;
play.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
play();
}
}) ;
Button stop = (Button)findViewById(R.id.end_bt) ;
stop.setEnabled(false) ;
stop.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
isRecording = false ;
findViewById(R.id.start_bt).setEnabled(true) ;
findViewById(R.id.end_bt).setEnabled(false) ;
}
}) ;
}
public void play() {
// Get the file we want to playback.
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/reverseme.pcm");
// Get the length of the audio stored in the file (16 bit so 2 bytes per short)
// and create a short array to store the recorded audio.
int musicLength = (int)(file.length()/2);
short[] music = new short[musicLength];
try {
// Create a DataInputStream to read the audio data back from the saved file.
InputStream is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
DataInputStream dis = new DataInputStream(bis);
// Read the file into the music array.
int i = 0;
while (dis.available() > 0) {
music[i] = dis.readShort();
i++;
}
// Close the input streams.
dis.close();
// Create a new AudioTrack object using the same parameters as the AudioRecord
// object used to create the file.
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT,
musicLength*2,
AudioTrack.MODE_STREAM);
// Start playback
audioTrack.play();
// Write the music buffer to the AudioTrack object
audioTrack.write(music, 0, musicLength);
audioTrack.stop() ;
} catch (Throwable t) {
Log.e("AudioTrack","Playback Failed");
}
}
public void record() {
int frequency = 11025;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/reverseme.pcm");
// Delete any previous recording.
if (file.exists())
file.delete();
// Create the new file.
try {
file.createNewFile();
} catch (IOException e) {
throw new IllegalStateException("Failed to create " + file.toString());
}
try {
// Create a DataOuputStream to write the audio data into the saved file.
OutputStream os = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(os);
DataOutputStream dos = new DataOutputStream(bos);
// Create a new AudioRecord object to record the audio.
int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
frequency, channelConfiguration,
audioEncoding, bufferSize);
short[] buffer = new short[bufferSize];
audioRecord.startRecording();
isRecording = true ;
while (isRecording) {
int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
for (int i = 0; i < bufferReadResult; i++)
dos.writeShort(buffer[i]);
}
audioRecord.stop();
dos.close();
} catch (Throwable t) {
Log.e("AudioRecord","Recording Failed");
}
}
}
2. XML布局 :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id = "@+id/start_bt" android:text = "Record Start"
android:textColor = "#DC143C" android:textStyle = "bold"
android:layout_width = "wrap_content" android:layout_height = "wrap_content"/>
<Button
android:id = "@+id/end_bt" android:text = "Record_Stop"
android:textColor = "#00008B" android:textStyle = "bold"
android:layout_width = "wrap_content" android:layout_height = "wrap_content"/>
<Button
android:id = "@+id/play_bt" android:text = "Play Record"
android:textStyle = "bold"
android:layout_width = "wrap_content" android:layout_height = "wrap_content"/>
</LinearLayout>
3. 权限 :
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
结束,再会!