(전) 안드로이드 멀티미디어 학습 10: 오디오 Record 클래스를 이용하여 자신의 오디오 녹화 프로그램 구현

7110 단어
Android 멀티미디어 학습 10: Audio Record 클래스를 이용하여 자신의 오디오 녹음 프로그램을 실현
 
 
Audio Record 클래스는 Media Recorder에 비해 밑바닥에 가깝고 우리를 위해 봉인하는 방법도 적다.오디오 Record를 실현하는 오디오 녹화 프로그램도
간단하다이 인스턴스 코드는 다음과 같습니다.
 
아쉽게도 본 실례 테스트 시 문제가 하나 있는데 녹화할 때 버퍼 오버가 발생합니다.캐시 누출이 해결되어야 합니다.
 
 
package demo.camera;
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 android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.hardware.Camera.AutoFocusCallback;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
 *     ,    AudioRecord             
 * AudioRecord ,           read         ,
 *             
 *  、     AudioRecord           
 * 1、AudioSource:     MediaRecorder.AudioSource.MIC
 * 2、SampleRateInHz:    ,   8000hz  11025hz ,            
 * 3、ChannelConfig:    ,   AudioFormat.CHANNEL_CONFIGURATION_MONO AudioFormat.CHANNEL_CONFIGURATION_STEREO
 * 4、AudioFormat:      ,   AudioFormat.ENCODING_16BIT 8BIT,  16BIT     8BIT ,                
 * 5、BufferSize:      :    getMinBufferSize   
 *             AudioRecord   
 *  、      ,         
 *    
 *  、       ,       
 * DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)))
 *  、          ,                AudioRecorder        ,  
 *   ,            AudioRecord      BufferSize
 * short[]buffer = new short[BufferSize/4];
 * startRecording();
 *       ,  AudioRecord read      
 *     MediaPlayer       AudioRecord      ,      ,    
 *   AudioTrack    
 * AudioTrack              
 * 
 * 
 *  、     AudioTrack         
 * 1、StreamType: AudioManager      ,     STREAM_MUSIC;
 * 2、SampleRateInHz:   AudioRecord        
 * 3、ChannelConfig:  
 * 4、AudioFormat:  
 * 5、BufferSize:  AudioTrack     getMinBufferSize   
 * 6、Mode:   AudioTrack.MODE_STREAM MODE_STATIC,         ,      
 *  、       ,             ,      ,      
 * 
 *    ,              AsyncTask    
 */
public class MyAudioRecord2 extends Activity{
	
	private TextView stateView;
	
	private Button btnStart,btnStop,btnPlay,btnFinish;
	
	private RecordTask recorder;
	private PlayTask player;
	
	private File audioFile;
	
	private boolean isRecording=true, isPlaying=false; //  
	
	private int frequence = 8000; //    ,  hz.       ,    ,     AudioRecord     ,   。     11025   。        
	private int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
	private int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
	
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_audio_record);
		
		stateView = (TextView)this.findViewById(R.id.view_state);
		stateView.setText("    ");
		btnStart = (Button)this.findViewById(R.id.btn_start);
		btnStop = (Button)this.findViewById(R.id.btn_stop);
		btnPlay = (Button)this.findViewById(R.id.btn_play);
		btnFinish = (Button)this.findViewById(R.id.btn_finish);
		btnFinish.setText("    ");
		btnStop.setEnabled(false);
		btnPlay.setEnabled(false);
		btnFinish.setEnabled(false);
		
		//           ,        
		File fpath = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/data/files/");
		fpath.mkdirs();//     
		try {
			//      ,        .pcm
			audioFile = File.createTempFile("recording", ".pcm", fpath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	
	public void onClick(View v){
		int id = v.getId();
		switch(id){
		case R.id.btn_start:
			//    
			
			//        
			recorder = new RecordTask();
			recorder.execute();
			
			break;
		case R.id.btn_stop:
			//    
			this.isRecording = false;
			//    
			//        , RecordTask onPostExecute   
			break;
		case R.id.btn_play:
			
			player = new PlayTask();
			player.execute();
			break;
		case R.id.btn_finish:
			//    
			this.isPlaying = false;
			break;
			
		}
	}
	
	class RecordTask extends AsyncTask{
		@Override
		protected Void doInBackground(Void... arg0) {
			isRecording = true;
			try {
				//           
				DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(audioFile)));
				//          ,          
				int bufferSize = AudioRecord.getMinBufferSize(frequence, channelConfig, audioEncoding);
				//   AudioRecord
				AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.MIC, frequence, channelConfig, audioEncoding, bufferSize);
				//    
				short[] buffer = new short[bufferSize];
				
				//    
				record.startRecording();
				
				int r = 0; //      
				//    ,  isRecording           
				while(isRecording){
					// bufferSize     ,     short  
					//      buffer overflow,        ,      ,   ,TODO:   
					int bufferReadResult = record.read(buffer, 0, buffer.length);
					//   buffer         OutputStream 
					for(int i=0; i{
		@Override
		protected Void doInBackground(Void... arg0) {
			isPlaying = true;
			int bufferSize = AudioTrack.getMinBufferSize(frequence, channelConfig, audioEncoding);
			short[] buffer = new short[bufferSize/4];
			try {
				//     ,      AudioTrack  ,    
				DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(audioFile)));
				//  AudioTrack
				AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, frequence, channelConfig, audioEncoding, bufferSize, AudioTrack.MODE_STREAM);
				//    
				track.play();
				//  AudioTrack     ,  ,            
				while(isPlaying && dis.available()>0){
					int i = 0;
					while(dis.available()>0 && i

 
Chenjie 19891104의 블로그(http://blog.csdn.net/chenjie19891104/article/category/756236)
나중에 공부하고 조회하세요!

좋은 웹페이지 즐겨찾기