我是初学者。我正在尝试使用代码中的按钮播放音轨但是当我正在运行应用程序时,应用程序没有正在运行。当我打开它时,它再次显示打开的应用程序它显示关闭应用程序.in log cat它显示运行时异常,说FATAL EXCEPTION:main / java.lang.RuntimeException:无法启动活动ComponentInfo {com.devlopers.colourplay / com.devlopers.colourplay.MainActivity}:java.lang.NullPointerException:Attempt to调用虚方法' int android.media.SoundPool.load(android.content.Context,int,int)'如果有人知道,请帮助我enter image description here
答案 0 :(得分:-1)
检查您是否以正确的方式初始化soundPool,
if (Build.VERSION.SDK_INT >= 21 ) {
AudioAttributes audioAttrib = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
SoundPool.Builder builder= new SoundPool.Builder();
builder.setAudioAttributes(audioAttrib).setMaxStreams(MAX_STREAMS);
this.soundPool = builder.build();
}
// for Android SDK < 21
else {
// SoundPool(int maxStreams, int streamType, int srcQuality)
this.soundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
}
检查声音池是否已加载:
// When Sound Pool load complete.
this.soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
loaded = true;
}
});
使用“loaded”标志播放声音。如果是真的那么只需要“玩”
详细参考: https://o7planning.org/en/10523/playing-sound-effects-in-android-with-soundpool