声音播放不一致

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

声音播放不一致。有时播放正确,但有时无法触发。

此问题似乎是随机发生的,似乎与任何特定的用户操作或设备配置无关。任何有关如何修复此错误的见解将不胜感激。

public class FActivity extends AppCompatActivity {
    private SoundPool soundPool;
    private int fSoundId;

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

        Button fButton = findViewById(R.id.f_button);
        fButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playFSound();
            }
        });
    }

    private void playFSound() {
        if (soundPool != null) {
            soundPool.play(fSoundId, 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;
        }
    }
}

f.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=".FActivity">

    <Button
        android:id="@+id/f_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sound"
        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.