MediaPlayer Class 사용

MediaPlayer의 기능을 사용해 보겠습니다.


간단한 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와 같은 오디오 파일을이 디렉토리에 복사합니다.
(주의 : 파일 이름은 소문자 전용)

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();
    }
}

좋은 웹페이지 즐겨찾기