簡単なI/Fを作ります。
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:onClick="onPlay"
/>
<Button
android:id="@+id/btnPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause"
android:onClick="onPausePlayer"/>
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:onClick="onStopPlayer"
/>
res->new resource directory->resource type(raw)->resource name(好きなように)、を作ります。そして、mp3かwavなどの音声ファイルをこのdirectoryにコピペします。
(注意:ファイル名は小文字オンリー)
MainActivity
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onPlay(View v){
/*MediaPlayer consumes too much memory resource
therefore we only create it when we want to play something
*/
if (mp==null){
/*makesure there's no old one before create new one
we don't want to create too much and use too many resource
*/
mp= MediaPlayer.create(this,R.raw.globe);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
DestroyPlayer();
}
});
}
mp.start();
}
public void onPausePlayer(View v){
if (mp!=null) mp.pause();
}
public void onStopPlayer(View v){
DestroyPlayer();
}
private void DestroyPlayer(){
if (mp!=null) mp.release();
mp=null;
Toast.makeText(this, "Media Player destroyed", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
super.onStop();
DestroyPlayer();
}
}