3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

BGMを再生する

Posted at

まずは流したいBGMを入れるためのフォルダを作りましょう
フォルダの名前はrawにしておきましょう。
その中に流したいBGMをいれます。

BGMを再生するためのクラスをしましょう。

MyBgm

public void MyBgm {

	private MediaPlayer mBgm;

	public MyBgm(Context context){

		//BGMファイルを読み込む
		this.mBgm = MediaPlayer.create(context, R.raw.「流したいBGMの名前」);
		this.mBgm.setLooping(true);
		this.mBgm.setVolume(1.0f, 1.0f);
	}

	//BGMを再生する
	public void start(){
		if (!mBgm.isPlaying()){
			mBgm.seekTo(0);
			mBgm.start();
		}
	}

	//BGMを停止する
	public void stop(){
		if (mBgm.isPlaying()) {
			mBgm.stop();
			mBgm.prepareAsync();
		}
	}
}

そして、再生したいclassに

	private MyBgm mBgm;

	public void onCreate(Bundle saveInstanceState) {

		・・・ 略 ・・・

		//イベントの追加
		this.mRetryButton.setOnclickListener(
			new Button.OnClickListener() {

		public void onClick(View v) {
			hideRetryButton();
			renderer.startNewGame();
		}
	});
	//MyBgmの生成
	this.mBgm = new MyBgm(this);
}

最後にonPauseとonResumeに停止と再生の処理を記述して終わりです。

public void onResume() {
				super.onResume();

	mBgm.start(); //BGM再生
}

public void onPause() {
	super.onPause();

	mBgm.stop(); //BGM停止

	・・・ 略 ・・・
}

それではビルドして正しく実行できるか試しましょう。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?