gpt4 book ai didi

android - Android产生声音

转载 作者:行者123 更新时间:2023-12-03 02:33:47 27 4
gpt4 key购买 nike

我写了这段代码来产生声音,但是我无法停止声音。当我按下开始按钮时,它会产生声音,但是当我按下结束按钮时,什么也不会发生。有人可以告诉我怎么了吗?

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;
}
}

最佳答案

您的genTone()方法在while(play)循环中阻止了UI线程。 UI线程忙于执行其他操作时,无法处理诸如按钮单击之类的UI事件。

经过一段时间后,UI线程被阻止的应用程序将被杀死为“应用程序无响应”。

考虑将背景线程用于长时间运行的音调生成循环。

关于android - Android产生声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30320389/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com