Created
October 16, 2014 04:24
-
-
Save akira-sasaki/d998c38259bd101cb49f to your computer and use it in GitHub Desktop.
Sound001
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package gclue.com.sound001; | |
import android.app.Activity; | |
import android.content.Context; | |
import android.graphics.Canvas; | |
import android.graphics.Color; | |
import android.media.MediaPlayer; | |
import android.os.Bundle; | |
import android.view.Menu; | |
import android.view.MenuItem; | |
import android.view.MotionEvent; | |
import android.view.View; | |
import java.io.IOException; | |
public class MyActivity extends Activity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
MyView mView = new MyView(this); | |
setContentView(mView); | |
} | |
@Override | |
public boolean onCreateOptionsMenu(Menu menu) { | |
// Inflate the menu; this adds items to the action bar if it is present. | |
getMenuInflater().inflate(R.menu.my, menu); | |
return true; | |
} | |
@Override | |
public boolean onOptionsItemSelected(MenuItem item) { | |
// Handle action bar item clicks here. The action bar will | |
// automatically handle clicks on the Home/Up button, so long | |
// as you specify a parent activity in AndroidManifest.xml. | |
int id = item.getItemId(); | |
if (id == R.id.action_settings) { | |
return true; | |
} | |
return super.onOptionsItemSelected(item); | |
} | |
} | |
/** | |
* 描画用のクラス. | |
*/ | |
class MyView extends View { | |
/** サウンド再生データを保持する. */ | |
private MediaPlayer mMediaPlayer; | |
/** | |
* コンストラクタ. | |
* @param context コンテキスト | |
*/ | |
public MyView( Context context ) { | |
super( context ); | |
// イベントが取得できるようにFocusを有効にする | |
setFocusable( true ); | |
// サウンドデータを読み込む(/res/raw/pon.mp3) | |
mMediaPlayer = MediaPlayer.create( context, R.raw.koto ); | |
} | |
/** | |
* 描画処理. | |
*/ | |
@Override | |
protected void onDraw( Canvas canvas ) { | |
// 背景色を設定する. | |
canvas.drawColor( Color.BLUE ); | |
} | |
/** | |
* タッチイベント。 | |
*/ | |
@Override | |
public boolean onTouchEvent( MotionEvent event ) { | |
if ( event.getAction() == MotionEvent.ACTION_DOWN ) { | |
// ACTION_DOWNは指が触れた時. | |
// 音の再生開始位置を0ミリセカンドの位置に設定する. | |
mMediaPlayer.seekTo(0); | |
// 音の再生を開始する. | |
mMediaPlayer.start(); | |
} else if ( event.getAction() == MotionEvent.ACTION_UP ) { | |
// ACTION_UPは指が離れた時. | |
// 音を停止する. | |
mMediaPlayer.stop(); | |
// 一度再生をstop()してから再び音を再生する場合は、prepare()を呼び出す必要がある | |
try { | |
mMediaPlayer.prepare(); | |
} catch ( IllegalStateException e ) { | |
e.printStackTrace(); | |
} catch ( IOException e ) { | |
e.printStackTrace(); | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment