Android Java将Audiorecord / Audiotrack保存到文件中

时间:2015-08-19 15:58:40

标签: android outputstream audiorecord audiotrack

如果用户按下开始按钮,我有一个简短的代码可以将录制的音频实时流式传输到扬声器。按下停止按钮后,缓冲的音频应保存在mp3文件中。文件已创建,但它是空的。如果我试着播放文件,我什么都听不到。

public class MainActivity extends Activity {
    boolean m_stop = true;
    AudioTrack m_audioTrack;
    Thread m_noiseThread;
    static final int bufferSize = 200000;
    AudioRecord arec;
    FileOutputStream os = null;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void onStartStopClicked(View v)
    {
        Button StartButton = (Button)findViewById(R.id.StartStop);
        if(m_stop) {
            start(); 
        } else {
            stop();
        }   
    }
    Runnable m_noiseGenerator = new Runnable()
    {       
        public void run()
        {
            String filepath = Environment.getExternalStorageDirectory().toString();
            os = new FileOutputStream(filepath + "/test.mp3");

            int buffersize1 = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
            arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize1);
            m_audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, 8000, AudioTrack.MODE_STREAM);

            byte[] buffer = new byte[buffersize1];
            arec.startRecording();
            m_audioTrack.play();
            while(!m_stop)
            {
                arec.read(buffer, 0, buffersize1);
                m_audioTrack.write(buffer, 0, buffer.length);    
                os.write(buffer);            
            }
        }
    };
    public void start()
    {
        m_stop = false;
        m_noiseThread = new Thread(m_noiseGenerator);
        m_noiseThread.start();
    }
    public void stop()
    {
        m_stop = true;    
        arec.stop();        
        m_audioTrack.stop();
        os.flush();
        os.close();
    }   
}

有人可以帮我解决这个问题吗?那将是非常感谢:)。

0 个答案:

没有答案