Android生成声音

时间:2015-05-19 08:27:09

标签: android audio

我写了这段代码来生成声音,但我无法停止声音。当我按下开始按钮时会产生声音,但按下结束按钮时没有任何反应。有人能告诉我出了什么问题吗?

private final int duration = 5; // seconds
private final int sampleRate = 8000;
private final int numSamples = duration * sampleRate;
private final double sample[] = new double[numSamples];
private final double freqOfTone = 250; // hz
private final byte generatedSnd[] = new byte[2 * numSamples];
Handler handler = new Handler();
private AudioTrack audioTrack;
private boolean play = false;
Button btnstart;
Button btnstop;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnstart= (Button)findViewById(R.id.StartSound);
    btnstop= (Button)findViewById(R.id.EndSound);
    btnstart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                    8000, AudioFormat.CHANNEL_OUT_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, numSamples,
                    AudioTrack.MODE_STREAM);
            play=true;
            audioTrack.play();
          //  playSound();
            genTone();

        }
    });
btnstop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    stopPlaying();
    audioTrack= new AudioTrack(AudioTrack.MODE_STREAM,8000,AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_16BIT,numSamples,AudioTrack.MODE_STREAM);
    audioTrack.play();


    }
});
    }



 void genTone(){
    // fill out the array
    while(play){
        for (int i = 0; i < numSamples; ++i) {
            //  float angular_frequency =
            sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone));
        }
        int idx = 0;

        // convert to 16 bit pcm sound array
        // assumes the sample buffer is normalised.
        for (double dVal : sample) {
            short val = (short) (dVal * 32767);
            generatedSnd[idx++] = (byte) (val & 0x00ff);
            generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
        }
        audioTrack.write(generatedSnd, 0, numSamples);
    }
}

  void stopPlaying() {
    if (audioTrack !=null){
        audioTrack.stop();
       audioTrack.release();
        audioTrack=null;        
}
    }

1 个答案:

答案 0 :(得分:0)

您的user_id report_date tBalance yBalance total_purchase_amt 3 20131106 0 0 0 4 20131106 0 0 5119808 方法阻止了其genTone()循环中的UI线程。当UI线程忙于做其他事情时,不能处理诸如按钮点击之类的UI事件。

阻止了UI线程的应用程序在一段时间后因“应用程序无响应”而被杀死。

考虑为长时间运行的音调生成循环使用后台线程。