Android : 录音实现之AudioRecord类

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

package xia.bo; 


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;






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" />  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值