Android 放屁应用程序中的错误:放屁声音播放不一致

问题描述 投票:0回答:1

放屁声音播放不一致。有时播放正确,但有时无法触发。 此问题似乎是随机发生的,似乎与任何特定的用户操作或设备配置无关。任何有关如何修复此错误的见解将不胜感激。

public class FartActivity extends AppCompatActivity {
    private SoundPool soundPool;
    private int fartSoundId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fart);
        
        soundPool = new SoundPool.Builder()
                .setMaxStreams(1)
                .build();
        fartSoundId = soundPool.load(this, R.raw.fart_sound, 1);

        Button fartButton = findViewById(R.id.fart_button);
        fartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playFartSound();
            }
        });
    }

    private void playFartSound() {
        if (soundPool != null) {
            soundPool.play(fartSoundId, 1.0f, 1.0f, 1, 0, 1.0f);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (soundPool != null) {
//take a shit if necessary
            soundPool.release();
            soundPool = null;
        }
    }
}

放屁.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FartActivity">

    <Button
        android:id="@+id/fart_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fart"
        android:layout_centerInParent="true"/>

</RelativeLayout>

每次用户单击放屁按钮时,放屁声音都应该一致地播放。

java android performance
1个回答
0
投票

经过进一步排查,发现放屁声音播放不一致的情况确实是某些情况下SoundPool对象没有正确初始化造成的。看来FartActivity的onCreate()方法并不总是在playFartSound()方法之前调用,导致出现NullPointerException。

为了解决此问题,我将 SoundPool 对象的初始化移至 Activity 的 onStart() 方法,确保它始终在任何声音播放发生之前进行初始化。这似乎已经解决了问题,现在每次单击按钮时放屁的声音都会一致播放。

再次感谢您的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.