gpt4 book ai didi

android - 为什么这个节拍器应用程序会崩溃? (安卓)

转载 作者:行者123 更新时间:2023-11-29 18:54:17 26 4
gpt4 key购买 nike

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

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

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

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

有谁知道为什么会发生这种崩溃?自 2013 年 3 月以来,此代码的作者在 Github 上有一个 Unresolved 错误/问题......所以我很确定这不是一个特别愚蠢的问题......如果你知道这个问题的答案,你会毫无疑问被誉为boss。

几天来,我一直在剖析代码、打印调试和研究 ASyncTask、Handlers 和 AudioTrack,但我无法弄清楚……如果没有人比我更厉害的话,我会的。

这是堆栈跟踪:

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中,如果你喜欢。

主要 Activity :

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

}

}

节拍器大脑:

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

}

音频发生器:

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>

最佳答案

思前想后dmarin的评论和阅读代码,我得出的结论是 dmarin回答了你的问题。这是一种竞争条件,也是对未初始化对象的访问。因此,简短 解决方案是:代码需要检查访问的数据是否已初始化。可以检查 AudioTrack 对象是否为 null 或者 getState() 是否等于“已初始化”。不幸的是,问题并没有随着我的设置而消失(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);
}

音频发生器

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

bool 值 play 由我重新调整用途。此外,当播放按钮被按下时,称为 currentBeat 的节拍计数器被重置。对于从 MainActivity 访问:将这些变量从 private 更改为 public 不是最佳解决方案。

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

MetronomeBrainplay() 中,循环变为无限循环。这个问题很快就会得到解决。这就是为什么可以重新调整 play bool 值的原因。音调的播放需要设置不同的条件,这取决于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 生命周期结束时完成,就像在 MainActivity 中这样:

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

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


引用资料
- 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:确保对象在访问它们之前已初始化,只需创建一次所有内容,并在不需要时销毁它们,例如在 Activity 结束时。

关于android - 为什么这个节拍器应用程序会崩溃? (安卓),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50244228/

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