gpt4 book ai didi

android - SoundPool 不播放声音

转载 作者:行者123 更新时间:2023-11-29 19:30:55 30 4
gpt4 key购买 nike

我正在尝试使用 SoundPool 在我的 Activity 中播放声音,但我听不到声音。

private void beginGame(){
setContentView(R.layout.activity_splash1);

if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
AudioAttributes aa = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_GAME)
.build();


sp = new SoundPool.Builder()
.setMaxStreams(10)
.setAudioAttributes(aa)
.build();
}else{
sp = new SoundPool(10, AudioManager.STREAM_MUSIC,1);
}

sid = sp.load(Splash1.this,R.raw.bubble,1);
sp.play(sid,1,1,1,0,0.99f);

Thread loading = new Thread() {
public void run() {
try {
sleep(2000);
// TODO NEXT ACTIVITY
}

catch (Exception e) {
e.printStackTrace();
}

finally {
finish();
}
}
};

loading.start();
}

最佳答案

最初,在我从事的一个项目中,我有一个像下面的 [AnswerSound] 这样的类,所以我总是获取它的实例并根据需要调用任何方法。我希望你能看看并从中解脱出来。

public class AnswerSound {
private final float volume;
private Context context;

private SoundPool correctAnswerSoundPool;
private int correctAnswerSoundID;
boolean correctLoaded = false;


private SoundPool wrongAnswerSoundPool;
private int wrongAnswerSoundID;
boolean wrongLoaded = false;
public AnswerSound(Context context)
{
this.context = context;
correctAnswerSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 10);
correctAnswerSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener(){
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
correctLoaded = true;
}
}
);

wrongAnswerSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 10);

wrongAnswerSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener()
{
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
wrongLoaded = true;
}
}

);
//assign the sound IDS
correctAnswerSoundID = correctAnswerSoundPool.load(context, R.raw.correct_answer, 1);

wrongAnswerSoundID = wrongAnswerSoundPool.load(context, R.raw.wrong_answer_sound_effect, 2);

//getting the user sound settings
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
volume = actualVolume / maxVolume;

//then you can play the sound by checking if the sound is loaded
}



public void playCorrectAnswerSound()
{
if (correctLoaded) {
correctAnswerSoundPool.play(correctAnswerSoundID, volume, volume, 1, 0, 1f);
}

}
public void playWrongAnswerSound() {
if (wrongLoaded) {
wrongAnswerSoundPool.play(wrongAnswerSoundID, volume, volume, 1, 0, 1f);
}
}

关于android - SoundPool 不播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39961512/

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