1

I'm working on a very small Android Project that uses this exact code from github.

However, when I (or you) intermittently button mash the start/stop button... the app eventually crashes. Unfortunately this can take a little while to reproduce... but it will happen!

Oh, I forgot the desired result!!

The desired result is that this crash does not occur. :)

Does anyone know why this crash occurs? The author of this code has had an open bug/issue for this on Github since March of 2013... so I'm pretty sure it's not a particularly stupid question... and if you do know the answer to this, you would no doubt be a hailed as a bowss.

I have been dissecting the code, print debugging, and researching ASyncTask, Handlers, and AudioTrack for a couple of days now but I can't figure it out... I will though if nobody else beats me to it.

This is the stack trace:

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) 

You could just go to github and download the original code, but in order to satisfy stackoverflow requirements, I have also provided the even-more-concise "minimal working example" which you can individually cut and paste into your Android Studio if you prefer.

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

Layout:

<?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>
4
  • 1
    Looks like you are calling play in a worker thread and stop in the main one, so I would say you are hitting a race condition where play is being called after stop. BTW you should not need to force the garbage collection
    – dmarin
    May 19, 2018 at 10:32
  • I just copy your code and run,Its working fine. There is no crash May 23, 2018 at 9:16
  • Might this link help? It seems they had the same problem. May 23, 2018 at 10:20
  • @Patel Jaimin : "Unfortunately this can take a little while to reproduce... but it will happen!" May 23, 2018 at 23:47

1 Answer 1

2
+100

After thinking about dmarin's comment and reading the code, I arrive to the conclusion that dmarin answered your question. It's a race condition, and it's also an access of an object which is not initialized. So the short solution is: The code needs to check, if the accessed data is initialized. The AudioTrack objects can be checked, if it is null or if the getState() equals "initialized". Unfortunately, the problem does not disappear with my setup (Android Studio 3.1.2, Android SDK Build-Tools 28-rc2).

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

After a code analysis one could notice the creation of AsyncTasks and AudioTracks. So, to minimize those, create the AsyncTask only once in the onCreate - function and set the AudioTrack object to 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;
    ...
}

I admit just changing it to static is not a beautiful solution. But since I only need one pipe to the AudioService, this will do.
Creating the audio-pipe, stopping the playing of the audio and freeing the resource will look like this:

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

The boolean play is repurposed by me. Also, the beat counter called currentBeat is reset, when the play button is pressed. For accessing from the MainActivity: The change from private to public of those variables is not the best solution.

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

In play() of MetronomeBrain the loop becomes an endless loop. This problem will be fixed, soon. That is why the play boolean may be repurposed. The playing of the tones needs to be set to a different condition, which depends on 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);
}

Now the loop runs forever, but it may only play, if play is set to true. If the clean-up is necessary, it may be done at the end of the Activity lifecycle like this in the MainActivity:

@Override
protected void onDestroy() {
    aSync.metronome.stopReleaseAudio(); //calls the stopRelease()
    aSync.cancel(true);
    super.onDestroy();
}

As I stated, the code could be further improved, but it gives a fair hint and enough material to think/learn about AsyncTasks, Services like Audio Service and Activity - Lifecycles.


References
- 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: Make sure that the objects are initialized before accessing them, just create everything once, and destroy them, when you do not need them e.g. at the end of the activity.

1
  • Thanks for the effort! May 24, 2018 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.