▼Androidメモ▼
サウンドの再生


サウンドを再生するプログラムを作成する。



リソース
サウンドファイル「sample.mp3」をNavigationbarのツリーの「res/raw」に挿入。


ソースコード
MediaPlayerEx.java
package net.npaka.mediaplayerex;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

//サウンドの再生
public class MediaPlayerEx extends Activity {
    private MediaPlayerView view;

    //アプリの初期化
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        view=new MediaPlayerView(this);
        setContentView(view);
    }

    //アプリの停止
    @Override
    public void onStop() {
        super.onStop();
        view.stopSound();
    }
}

MediaPlayerView.java
package net.npaka.mediaplayerex;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.view.MotionEvent;
import android.view.View;

//サウンドの再生
public class MediaPlayerView extends View
    implements MediaPlayer.OnCompletionListener {
    private MediaPlayer player;  //プレーヤー
    private boolean     playFlag;//再生フラグ

    //コンストラクタ
    public MediaPlayerView(Context context) {
        super(context);
        setBackgroundColor(Color.WHITE);
        setFocusable(true);
        player  =null;
        playFlag=false;
    }

    //描画
    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint=new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(16);
        canvas.drawText("MediaPlayerEx2",0,20,paint);
    }

    //タッチイベントの処理
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction()==MotionEvent.ACTION_DOWN) {
            if (playFlag==false) {
                playFlag=true;
                playSound();
            } else {
                playFlag=false;
                stopSound();
            }
        }
        return true;
    }

    //サウンドの再生
    public void playSound() {
        try {
            player=MediaPlayer.create(getContext(),R.raw.hoge);
            player.start();
            player.setOnCompletionListener(this);
        } catch (Exception e) {
        }
    }

    //サウンドの停止
    public void stopSound() {
        try {
            player.stop();
            player.setOnCompletionListener(null);
            player.release();
            player=null;
        } catch (Exception e) {
        }
    }

    //サウンド再生終了時に呼ばれる
    public void onCompletion(MediaPlayer mediaPlayer) {
    }
}



−戻る−