音声ファイルを再生する


Androidで音声ファイルを再生するためにはMediaPlayerクラスを使います。
MediaPlayerクラスが提供するメソッドを利用することで、簡単に音声ファイルを再生することができます。

詳細は続きからどうぞ。

まず、再生したい音声ファイルをrawディレクトリ以下に保存します。
今回はsample.mp3という音声ファイルを作成しました。
(rawディレクトリはデフォルトで存在しないので、ディレクトリも新たに作成します)

次にレイアウトファイルですが、今回は上記スクリーンショットのように
再生/停止用のボタンを1つだけ用意して、音声ファイルの再生中/停止中のチェックをして
ラベルを動的に変更します。

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button android:text="Music Start" android:id="@+id/PlayButton" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>

そしてソースコードです。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package org.jpn.techbooster.MediaPlayerSample;
 
import java.io.IOException;
 
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class MediaPlayerSample extends Activity implements OnClickListener {
    MediaPlayer mp = null;
    Button play_button;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        mp = MediaPlayer.create(this, R.raw.sample);
 
        play_button = (Button) findViewById(R.id.PlayButton);
        play_button.setOnClickListener(this);
    }
 
    public void onClick(View v) {
        if (mp.isPlaying()) { //再生中
            play_button.setText("Music Start");
            mp.stop();
            try {
                mp.prepare();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else { //停止中
            play_button.setText("Music Stop");
            mp.start();
        }
    }
}

実装の内容はとてもシンプルで、まずMediaPlayer.createメソッドでsample.mp3を指定しています。
そして、ボタンを押したときに呼ばれるonClickコールバック内では、mp.isPlaying()を使って
MediaPlayerが停止中か再生中かチェックします。
停止中であればmp.start()で音声ファイルを再生開始、再生中であれば
mp.stop()で音声ファイルを停止させています。なお、停止させる際にはmp.prepare()
併せて実行しないと、再度再生することができないので注意してください。

3 Comments