SoundPool没有播放声音

时间:2016-10-10 15:16:30

标签: android soundpool

我正在尝试使用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(); } 在我的活动中播放声音,但我无法听到声音。

@IBOutlet weak var button: UIButton!

1 个答案:

答案 0 :(得分:2)

最初,在我工作的一个项目中,我有一个像[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);
    }
}

}