Android中的简单实时麦克风

时间:2013-04-09 01:23:06

标签: android audio real-time

我从Pro Android媒体书中得到了帮助......

以下是代码:

public class MicMeter extends Activity implements OnClickListener {


RecordAudio recordTask;
int blocksize = 256;
int frequency = 8000;
int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
TextView txt;
Button start;
boolean started = false;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mic_meter);
    start = (Button)findViewById(R.id.button1);
    txt = (TextView)findViewById(R.id.textView1);

    start.setOnClickListener(this);


}


private class RecordAudio extends AsyncTask <Void,double[],Void>{

    @Override
    protected Void doInBackground(Void... params) {
        try{
        int bufferSize = AudioRecord.getMinBufferSize(frequency,channelConfig,audioEncoding);
        AudioRecord audioRecord = new AudioRecord( MediaRecorder.AudioSource.MIC, frequency, channelConfig, audioEncoding, bufferSize);

        short[] buffer = new short[blocksize];
        double[] meter = new double[blocksize];

        audioRecord.startRecording();

        while(started){
            int bufferReadResult = audioRecord.read(buffer, 0, blocksize);

            for (int i = 0; i < blocksize && i < bufferReadResult; i++) { 
                meter[i] = (double) buffer[i] / 32768.0; // signed 16 bit
            }
            publishProgress(meter);
        }
        audioRecord.stop();

    }catch (Throwable t) {
        Log.e("AudioRecord","RecordingFail");
    }

        return null;
    }

    @Override
    protected void onProgressUpdate(double[]... meter) {

        for(int i = 0 ; i < meter[0].length ; i++){
            double[] helper = meter[i];
            txt.setText(Double.toString(helper));
        }

    }


}


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    if(started){
        recordTask.cancel(true);
    }else{
        started = true;
        recordTask = new RecordAudio();
        recordTask.execute();

    }
}

}

我按下按钮。 它显示255.0然后它没有响应... 有没有办法解决它? 有没有关于此的beter版本?

感谢

1 个答案:

答案 0 :(得分:0)

for(int i = 0 ; i < meter[0].length ; i++){
    double helper = i;
    txt.setText(Double.toString(helper));

setText会覆盖旧值。所以只会显示最后一个电话。最后一个调用将其设置为helper,它始终为meter [0] .length。由于这是固定数字,因此不会改变。