gpt4 book ai didi

android - android如何在按下按钮时停止音频线程?

转载 作者:行者123 更新时间:2023-12-02 23:44:08 25 4
gpt4 key购买 nike

我有一个线程使用AudioTrack来合成音符序列,并带有一个搜索栏来更改速度。

t = new Thread()
{
public void run()
{
setPriority(Thread.MAX_PRIORITY);

int buffersize = AudioTrack.getMinBufferSize(sr, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT);

audiotrack = new AudioTrack(AudioManager.STREAM_MUSIC, sr,
AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
buffersize, AudioTrack.MODE_STREAM);

short samples[] = new short[buffersize];

int amplitude = 10000;
double twopi = 2*Math.PI;

double ph = 0.0;


audiotrack.play();
double r = 1.0594630943593; //the 12th root of 2
frequency=261.63;
for(int k = 1; k<9; k++) //number of notes played
{
frequency*=r;
for (int i = 0; i < 4+4*temposliderval; i++) //duration of each note, if i = 50, note duration = 12 seconds
{

for (int j = 0; j < buffersize; j++)
{
samples[j] = (short) (amplitude * Math.sin(ph));
ph += twopi * frequency / sr;
}
audiotrack.write(samples, 0, buffersize);
}
}

audiotrack.stop();
audiotrack.release();

}
};


//play button
play = (Button)findViewById(R.id.play);
play.setBackgroundResource(R.mipmap.play);
play.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
t.start();
}
});







//stop button
stop = (Button)findViewById(R.id.stop);
stop.setBackgroundResource(R.mipmap.stop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
t.interrupt();
}
});

我希望能够在按下停止按钮时停止音频。调用t.interrupt()不起作用,所以 我想知道如何在按下停止按钮时正确地停止线程。 目标是能够在需要时停止音频,并在再次按下播放按钮时再次将其备份。

最佳答案

最简单的操作可能是声明一个volatile成员变量:

private volatile boolean mStop = false;

这两个线程都可以访问。您可以在线程的循环内部轮询变量,并在设置线程时停止循环,并在按下按钮时将变量设置为true。

关于android - android如何在按下按钮时停止音频线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33861459/

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