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) {
}
} |