/res/layout/ main.xml
<?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"
android:background="#ffffff" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="My Beep" />
<Button android:text="Play"
android:id="@+id/Button01"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
<Button android:text="Pause"
android:id="@+id/Button02"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
<Button android:text="Stop"
android:id="@+id/Button03"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
</LinearLayout>
/src/ubu.example.MyBeep/myBeep.java
package ubu.example.MyBeep;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MyBeep extends Activity {
private MediaPlayer mMediaPlayer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMediaPlayer = MediaPlayer.create(this, R.raw.mum);
mMediaPlayer.setLooping(false);
Button play = (Button) findViewById(R.id.Button01);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
playAudio();
}
});
Button pause = (Button) findViewById(R.id.Button02);
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pauseAudio();
}
});
Button stop = (Button) findViewById(R.id.Button03);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
stopAudio();
}
});
}
private void playAudio() {
try {
Log.e("beep", "started0");
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
finish();
}
});
} catch (Exception e) {
Log.e("beep", "error: " + e.getMessage(), e);
}
}
private void pauseAudio() {
try {
Log.e("beep", "started0");
mMediaPlayer.pause();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
finish();
}
});
} catch (Exception e) {
Log.e("beep", "error: " + e.getMessage(), e);
}
}
private void stopAudio() {
try {
Log.e("beep", "started0");
mMediaPlayer.stop();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
finish();
}
});
} catch (Exception e) {
Log.e("beep", "error: " + e.getMessage(), e);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
}

ไม่มีความคิดเห็น:
แสดงความคิดเห็น