如何在Android上播放音频

时间:2015-01-08 10:28:50

标签: android audio

我开发了Android游戏应用程序。我想在用户玩游戏时播放背景音乐,用户可以在禁用音乐复选框上禁用该音乐。 你能不能给我任何想法,我怎么能在游戏活动中做到这一点。

此致

2 个答案:

答案 0 :(得分:0)

这种技术是用来播放背景声音的。

private SoundBroadCastReceiver soundBroadCast;
private void registerBroadCast() {
    soundBroadCast = new SoundBroadCastReceiver();
    IntentFilter intentfilter = new IntentFilter();
    intentfilter.addAction("android.intent.action.USER_PRESENT");
    registerReceiver(soundBroadCast, intentfilter);
}

    private class SoundBroadCastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        startMusic();
    }
}

 MediaPlayer mediaPlayer = new MediaPlayer();  
private void startMusic() {
    if (mediaPlayer != null) {
        mediaPlayer = null;
    }
    mediaPlayer = MediaPlayer.create(this, R.raw.main_screen);
    mediaPlayer.setLooping(true);
    if (!mediaPlayer.isPlaying()) {

            mediaPlayer.start();


    }
}

private void stopMusic() {
    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
    }
}







@Override
protected void onResume() {

    if (!((KeyguardManager) getSystemService("keyguard"))
            .inKeyguardRestrictedInputMode()) {
        startMusic();
    }

    registerBroadCast();
    super.onResume();

}

@Override
protected void onPause() {
    unregisterReceiver(soundBroadCast);
    stopMusic();
    System.gc();
    super.onPause();


}

答案 1 :(得分:0)

您可以使用布尔变量,例如mMusicButtonOn并初步设置为false,并在您的游戏启动方法和禁用音乐复选框中使用此类

if( !mMusicButtonOn ){

    //do Music On
    mMusicButtonOn=true;
    mMainGameScene.playMusic(MusicFileNames.MAIN_MENU_SOUND);

}
else {
    //do Music Off
    mMusicButtonOn=false;
    mMainGameScene.pauseAllMusic();
    }