android - 将录音保存在缓冲区中并稍后播放

时间:2012-12-25 00:59:37

标签: android

我正在尝试录制没有保存声音文件的录音,我使用AudioRecord将录音保存在缓冲区中,使用AudioTrack播放声音,以便稍后点击“播放”按钮

这是我的应用程序代码源

package com.stackoverflow.sofproject;

import java.io.IOException;

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.util.Log;
import android.view.View;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

    boolean recorder = true;
    AudioRecord ar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final int minSize = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
        ar = new AudioRecord(MediaRecorder.AudioSource.MIC,
                8000,AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,minSize);


        final short[] buffer = new short[minSize];

        ar.startRecording();        
        Log.e("SoundRecordingActivity", "Start record !");

        Thread Rthread = new Thread(new Runnable() {
            public void run() {
                while(recorder)
                {
                    ar.read(buffer, 0, minSize);
                }
            }
        });
        Rthread.start();
    }

    public void stopRecordButtonAndPlayBack(){
        ar.stop();
        recorder = false;
        Log.e("SoundRecordingActivity", "Stop record !");
        // play sound
        int minSize = AudioRecord.getMinBufferSize(8000,AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
        ar = new AudioRecord(MediaRecorder.AudioSource.MIC,
                8000,AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,minSize);

        AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                8000,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                 AudioFormat.ENCODING_PCM_16BIT,
                minSize,
                AudioTrack.MODE_STREAM);

        audioTrack.play();

        while (true) {
            audioTrack.write(buffer, 0, minSize);
        }           
    }
}

录音工作正常

当我录制播放按钮(stopRecordButtonAndPlayBack)时,app强制关闭

问题不在button和stopRecordButtonAndPlayBack之间的链接中 如何将缓冲区作为声音播放的问题

抱歉我的英文

0 个答案:

没有答案