1

我正在尝试在不保存声音文件的情况下进行录制,我使用 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)时,应用程序强制关闭

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

对不起我的英语不好

4

0 回答 0