AudioTrack:从线程开始调用

时间:2012-01-23 18:14:14

标签: android audio audiotrack

我在静态模式下使用AudioTrack一遍又一遍地重现相同的信号。

我已经按照这里的示例进行了操作,有时它可以完美地工作,但有时会抛出此错误并且不会产生声音:

AudioTrack: start called from a thread
01-23 15:26:16.902: W/libutils.threads(1133): Thread (this=0x3973b8): don't call waitForExit() from this Thread object's thread. It's a guaranteed deadlock!

这是源代码。我正在努力确保我调用stop并重新加载数据以进行下一次“播放”执行。

     public class SoundPlayer {
     // originally from http://marblemice.blogspot.com/2010/04/generate-and-play-tone-in-android.html
        private int numSamples;
        private double sample[];
        private byte generatedSnd[];
        private AudioTrack audioTrack;

        public SoundPlayer(float duration, int sampleRate, double freqOfTone) {
            super();
            this.numSamples = (int) (duration * sampleRate);
            this.sample = new double[numSamples];
            this.generatedSnd = new byte[2 * numSamples];
            // fill out the array
            for (int i = 0; i < numSamples; ++i) {
                sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / freqOfTone));
            }
            // convert to 16 bit pcm sound array
            // assumes the sample buffer is normalised.
            int idx = 0;
            for (final double dVal : sample) {
                // scale to maximum amplitude
                final short val = (short) ((dVal * 32767));
                // in 16 bit wav PCM, first byte is the low order byte
                generatedSnd[idx++] = (byte) (val & 0x00ff);
                generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);

            }
            audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                    sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT, numSamples,
                    AudioTrack.MODE_STATIC);
            audioTrack.write(generatedSnd, 0, generatedSnd.length);
        }

        public void playSound() {
            if ( audioTrack.getPlayState() ==  (AudioTrack.PLAYSTATE_PLAYING | AudioTrack.PLAYSTATE_PAUSED )) {
                audioTrack.stop();
                audioTrack.reloadStaticData();
            }
            Log.i("Audio", "playState: " + audioTrack.getPlayState());
            audioTrack.play();
            audioTrack.stop();
            audioTrack.reloadStaticData();
        }

}

如果我们打开android源代码,它并没有解释很多:

void AudioTrack::start()
{
sp<AudioTrackThread> t = mAudioTrackThread;

LOGV("start");
if (t != 0) {
    if (t->exitPending()) {
        if (t->requestExitAndWait() == WOULD_BLOCK) {
            LOGE("AudioTrack::start called from thread");
            return;
        }
    }
    t->mLock.lock();
 } 

有谁知道如何处理这个问题?

1 个答案:

答案 0 :(得分:4)

我曾经遇到过类似的问题。

简单地说,如果您碰巧在多个主题中运行了某些内容,则必须确保创建AudioTrack并在其上调用play()stop() 发生在同一个帖子中。

但是,这并不意味着您必须在该线程中创建音频样本。如果您使用静态音频数据(AudioTrack.MODE_STATIC),您可以在其他地方预加载或生成它们,然后在应用程序的整个生命周期内多次使用它。