結果如以下連結
貓咪音效
主要是利用
1.ImageButton
2. MediaPlayer
--
public class MediaDemo extends Activity {
/**宣告一個全域變數mp*/
private MediaPlayer mp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 宣告一個圖像按鈕;MediaPlayer初始化
ImageButton ButPlay = (ImageButton) findViewById(R.id.imageButton1);
mp = MediaPlayer.create(MediaDemo.this,R.raw.ooh);
ButPlay.setOnClickListener(play);
// 宣告一個結束按鈕
Button Exitmp = (Button)findViewById(R.id.button1);
Exitmp.setOnClickListener(stopmp);
}
private OnClickListener play = new OnClickListener(){
public void onClick(View v){
if(mp.isPlaying()){
mp.stop();
// 因為mp.stop()會直接把MediaPlayer整個關掉,因此要重新給它初始化
mp = MediaPlayer.create(MediaDemo.this,R.raw.ooh);
}
mp.start();
}
};
private OnClickListener stopmp = new OnClickListener(){
public void onClick(View v){
// MediaPlay是在背景播放的,所以離開app必須連MediaPlayer也要關掉
mp.stop();
MediaDemo.this.finish();
}
};
}
--
沒有留言:
張貼留言