为什么这个节拍器应用程序会崩溃? (机器人)

时间:2018-05-09 01:21:38

标签: android memory stream buffer audiotrack

我正在开发一个使用this exact code from github的非常小的Android项目。

然而,当我(或你)间歇性地按下混合开始/停止按钮时......应用程序最终会崩溃。不幸的是,这可能需要一段时间才能重现...但它会发生!

哦,我忘了想要的结果!!

  

期望的结果是不会发生此崩溃。 :)

有谁知道这次崩溃的原因?自2013年3月以来,这段代码的作者在Github上有一个开放的bug /问题......所以我很确定这不是一个特别愚蠢的问题......如果你确实知道答案,你会无疑是一个被誉为弓箭的人。

我已经解密了代码,打印调试,并且研究ASyncTask,Handlers和AudioTrack已经有几天了,但是我无法弄清楚......如果没有其他人打败我的话,我会这样做。< / p>

这是堆栈跟踪:

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
                  Process: com.example.boober.beatkeeper, PID: 15664
                  java.lang.RuntimeException: An error occurred while executing doInBackground()
                      at android.os.AsyncTask$3.done(AsyncTask.java:309)
                      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                      at java.lang.Thread.run(Thread.java:818)
                   Caused by: java.lang.IllegalStateException: Unable to retrieve AudioTrack pointer for write()
                      at android.media.AudioTrack.native_write_byte(Native Method)
                      at android.media.AudioTrack.write(AudioTrack.java:1761)
                      at android.media.AudioTrack.write(AudioTrack.java:1704)
                      at com.example.boober.beatkeeper.AudioGenerator.writeSound(AudioGenerator.java:55)
                      at com.example.boober.beatkeeper.Metronome.play(Metronome.java:60)
                      at com.example.boober.beatkeeper.MainActivity$MetronomeAsyncTask.doInBackground(MainActivity.java:298)
                      at com.example.boober.beatkeeper.MainActivity$MetronomeAsyncTask.doInBackground(MainActivity.java:283)
                      at android.os.AsyncTask$2.call(AsyncTask.java:295)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                      at java.lang.Thread.run(Thread.java:818) 

您可以直接访问github并下载原始代码,但为了满足stackoverflow的要求,我还提供了更简洁的“最小工作示例”,您可以单独剪切并粘贴到Android Studio中你更喜欢。

MainActivity:

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    String TAG = "AAA";

    Button playStopButton;
    TextView currentBeat;

    // important objects
    MetronomeAsyncTask aSync;
    Handler mHandler;

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

        currentBeat = findViewById(R.id.currentBeatTextView);
        playStopButton = findViewById(R.id.playStopButton);

        // important objcts
        aSync = new MetronomeAsyncTask();
    }


    // only called from within playStopPressed()
    private void stopPressed() {
        aSync.stop();
        aSync = new MetronomeAsyncTask();
    }
    // only called from within playStopPressed()
    private void playPressed() {
        //aSync.execute();
        aSync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
    }
    public synchronized void playStopButtonPressed(View v) {
        boolean wasPlayingWhenPressed = playStopButton.isSelected();
        playStopButton.setSelected(!playStopButton.isSelected());
        if (wasPlayingWhenPressed) {
            stopPressed();
        } else {
            playPressed();
        }
    }

    // METRONOME BRAIN STUFF ------------------------------------------

    private Handler getHandler() {
        return new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String message = (String) msg.obj;
                if (message.equals("1")) {
                    currentBeat.setTextColor(Color.GREEN);
                    }
                else {
                    currentBeat.setTextColor(Color.BLUE);
                }

                currentBeat.setText(message);
            }
        };
    }


    private class MetronomeAsyncTask extends AsyncTask<Void, Void, String> {
        MetronomeBrain metronome;

        MetronomeAsyncTask() {
            mHandler = getHandler();
            metronome = new MetronomeBrain(mHandler);
            Runtime.getRuntime().gc();    // <---- don't know if this line is necessary or not.
        }

        protected String doInBackground(Void... params) {
            metronome.setBeat(4);
            metronome.setNoteValue(4);
            metronome.setBpm(100);
            metronome.setBeatSound(2440);
            metronome.setSound(6440);
            metronome.play();
            return null;
        }

        public void stop() {
            metronome.stop();
            metronome = null;
        }

        public void setBpm(short bpm) {
            metronome.setBpm(bpm);
            metronome.calcSilence();
        }

        public void setBeat(short beat) {
            if (metronome != null)
                metronome.setBeat(beat);
        }

    }

}

MetronomeBrain:

import android.os.Handler;
import android.os.Message;

public class MetronomeBrain {

    private double bpm;
    private int beat;
    private int noteValue;
    private int silence;

    private double beatSound;
    private double sound;
    private final int tick = 1000; // samples of tick

    private boolean play = true;

    private AudioGenerator audioGenerator = new AudioGenerator(8000);
    private Handler mHandler;
    private double[] soundTickArray;
    private double[] soundTockArray;
    private double[] silenceSoundArray;
    private Message msg;
    private int currentBeat = 1;

    public MetronomeBrain(Handler handler) {
        audioGenerator.createPlayer();
        this.mHandler = handler;
    }

    public void calcSilence() {
        silence = (int) (((60 / bpm) * 8000) - tick);
        soundTickArray = new double[this.tick];
        soundTockArray = new double[this.tick];
        silenceSoundArray = new double[this.silence];
        msg = new Message();
        msg.obj = "" + currentBeat;
        double[] tick = audioGenerator.getSineWave(this.tick, 8000, beatSound);
        double[] tock = audioGenerator.getSineWave(this.tick, 8000, sound);
        for (int i = 0; i < this.tick; i++) {
            soundTickArray[i] = tick[i];
            soundTockArray[i] = tock[i];
        }
        for (int i = 0; i < silence; i++)
            silenceSoundArray[i] = 0;
    }

    public void play() {
        calcSilence();
        do {
            msg = new Message();
            msg.obj = "" + currentBeat;
            if (currentBeat == 1)
                audioGenerator.writeSound(soundTockArray);
            else
                audioGenerator.writeSound(soundTickArray);
            if (bpm <= 120)
                mHandler.sendMessage(msg);
            audioGenerator.writeSound(silenceSoundArray);
            if (bpm > 120)
                mHandler.sendMessage(msg);
            currentBeat++;
            if (currentBeat > beat)
                currentBeat = 1;
        } while (play);
    }

    public void stop() {
        play = false;
        audioGenerator.destroyAudioTrack();
    }

    public double getBpm() {
        return bpm;
    }

    public void setBpm(int bpm) {
        this.bpm = bpm;
    }

    public int getNoteValue() {
        return noteValue;
    }

    public void setNoteValue(int bpmetre) {
        this.noteValue = bpmetre;
    }

    public int getBeat() {
        return beat;
    }

    public void setBeat(int beat) {
        this.beat = beat;
    }

    public double getBeatSound() {
        return beatSound;
    }

    public void setBeatSound(double sound1) {
        this.beatSound = sound1;
    }

    public double getSound() {
        return sound;
    }

    public void setSound(double sound2) {
        this.sound = sound2;
    }

}

AudioGenerator:

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

public class AudioGenerator {

    private int sampleRate;
    private AudioTrack audioTrack;

    public AudioGenerator(int sampleRate) {
        this.sampleRate = sampleRate;
    }

    public double[] getSineWave(int samples,int sampleRate,double frequencyOfTone){
        double[] sample = new double[samples];
        for (int i = 0; i < samples; i++) {
            sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/frequencyOfTone));
        }
        return sample;
    }

    public byte[] get16BitPcm(double[] samples) {
        byte[] generatedSound = new byte[2 * samples.length];
        int index = 0;
        for (double sample : samples) {
            // scale to maximum amplitude
            short maxSample = (short) ((sample * Short.MAX_VALUE));
            // in 16 bit wav PCM, first byte is the low order byte
            generatedSound[index++] = (byte) (maxSample & 0x00ff);
            generatedSound[index++] = (byte) ((maxSample & 0xff00) >>> 8);

        }
        return generatedSound;
    }

    public void createPlayer(){
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                AudioFormat.ENCODING_PCM_16BIT, sampleRate,
                AudioTrack.MODE_STREAM);
        audioTrack.play();
    }

    public void writeSound(double[] samples) {
        byte[] generatedSnd = get16BitPcm(samples);
        audioTrack.write(generatedSnd, 0, generatedSnd.length);
    }

    public void destroyAudioTrack() {
        audioTrack.stop();

        // This line seems to be a most likely culprit of the start/stop crash.
        // Is this line even necessary?
        audioTrack.release();
    }
}

布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.boober.android_metronome.MainActivity">

    <Button
        android:id="@+id/playStopButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:onClick="playStopButtonPressed"
        android:text="Play"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/currentBeatTextView"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:text="TextView"
        android:gravity="center_vertical"
        android:textAlignment="center"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/playStopButton" />

</android.support.constraint.ConstraintLayout>

1 个答案:

答案 0 :(得分:2)

在考虑dmarin的评论并阅读代码后,我得出dmarin回答了您的问题的结论。它是一种竞争条件,它也是一个未初始化的对象的访问。所以 short 解决方案是:代码需要检查,如果访问的数据是初始化的。可以检查AudioTrack个对象,如果它是null,或者getState()等于&#34;已初始化&#34;。不幸的是,我的设置(Android Studio 3.1.2,Android SDK Build-Tools 28-rc2)问题并没有消失。

private boolean isInitialized() {
    return audioTrack.getState() == AudioTrack.STATE_INITIALIZED;
}

在进行代码分析后,可以注意到AsyncTasks和AudioTracks的创建。因此,要最小化这些,请在onCreate - 函数中仅创建一次AsyncTask,并将AudioTrack对象设置为static

<强> MainActivity

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

    currentBeat = findViewById(R.id.currentBeatTextView);
    playStopButton = findViewById(R.id.playStopButton);

    // important objcts
    aSync = new MetronomeAsyncTask();
    aSync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
}

AudioGenerator

public class AudioGenerator {
    /*changed to static*/
    private static AudioTrack audioTrack;
    ...
}

我承认只是将它改为静态不是一个漂亮的解决方案。但由于我只需要一个管道连接到AudioService,这样做 创建音频管道,停止播放音频和释放资源将如下所示:

public void createPlayer(){
    if (audioTrack == null  || ! isInitialized())
    audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
            sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO,
            AudioFormat.ENCODING_PCM_16BIT, sampleRate,
            AudioTrack.MODE_STREAM);
    if (isInitialized()){
        audioTrack.play();
    }
}
public void destroyAudioTrack() {
    if (isInitialized()) {
        audioTrack.stop();
    }
}
public void stopRelease() {
    if (isInitialized()) {
        audioTrack.stop();
        audioTrack.release();
    }
}

布尔play被我改变了用途。此外,当按下播放按钮时,重置称为currentBeat的节拍计数器。要从MainActivity进行访问:从这些变量privatepublic的更改不是最佳解决方案。

// only called from within playStopPressed()
private void stopPressed() {
    aSync.metronome.play = false;
}
// only called from within playStopPressed()
private void playPressed() {
    aSync.metronome.play = true;
    aSync.metronome.currentBeat = 1;
}

play() MetronomeBrain中,循环变为无限循环。很快就会解决这个问题。这就是为什么play布尔值可以改变用途的原因。音调的播放需要设置为不同的条件,这取决于play

public void play() {
    calcSilence();
/*a change for the do-while loop: It runs forever and needs
  to be killed externally of the loop.
  Also the play decides, if audio is being played.*/
    do {
        msg = new Message();
        msg.obj = "" + currentBeat;
        if (currentBeat == 1 && play)
            audioGenerator.writeSound(soundTockArray);
        else if (play)
            audioGenerator.writeSound(soundTickArray);
        if (bpm <= 120)
            mHandler.sendMessage(msg);
        audioGenerator.writeSound(silenceSoundArray);
        if (bpm > 120)
            mHandler.sendMessage(msg);
        currentBeat++;
        if (currentBeat > beat)
            currentBeat = 1;
    } while (true);
}

现在循环会永远运行,但只有在play设置为true时才可以播放。如果需要进行清理,可以在Activity的{​​{1}}生命周期结束时进行清理:

MainActivity

正如我所说,代码可以进一步改进,但它提供了一个公平的提示和足够的材料来思考/了解AsyncTasks,音频服务和活动 - 生命周期等服务。

<强>参考
  - https://developer.android.com/reference/android/os/AsyncTask
  - https://developer.android.com/reference/android/media/AudioManager
  - https://developer.android.com/reference/android/media/AudioTrack
  - https://developer.android.com/reference/android/app/Activity#activity-lifecycle

TL; DR :确保在访问对象之前初始化对象,只需创建一次,然后在不需要时将其销毁,例如:在活动结束时。