[Android MediaPlayer #2] 기본 사용법

Posted by [하늘이]
2010. 11. 24. 14:57 IT/Android[안드로이드]
반응형

 MediaPlayer Class 기본 사용 [2]
MediaPlayer 를 확인해보면, 아래와 같은 리스너들이 있습니다.

Nested Classes
interface MediaPlayer.OnBufferingUpdateListener Interface definition of a callback to be invoked indicating buffering status of a media resource being streamed over the network. 
interface MediaPlayer.OnCompletionListener Interface definition for a callback to be invoked when playback of a media source has completed. 
interface MediaPlayer.OnErrorListener Interface definition of a callback to be invoked when there has been an error during an asynchronous operation (other errors will throw exceptions at method call time). 
interface MediaPlayer.OnInfoListener Interface definition of a callback to be invoked to communicate some info and/or warning about the media or its playback. 
interface MediaPlayer.OnPreparedListener Interface definition for a callback to be invoked when the media source is ready for playback. 
interface MediaPlayer.OnSeekCompleteListener Interface definition of a callback to be invoked indicating the completion of a seek operation. 
interface MediaPlayer.OnVideoSizeChangedListener Interface definition of a callback to be invoked when the video size is first known or updated  

그중에 두가지만 사용하면 Play와 에러 발생에 대해서 처리 할 수 있습니다.

 => 예제 코드중에 회색 배경 코드는 제가 만든것이니 참고하세요.
[그냥 넣으시면 에러발생합니다.]


1. Play 완료 된 상태를 알수 있는 방법.  

public void setOnCompletionListener (MediaPlayer.OnCompletionListener listener)

Since: API Level 1

Register a callback to be invoked when the end of a media source has been reached during playback.

Parameters
listener the callback that will be run

Mediaplayer에 callback을 등록시켜 놓으면, play완료 된 후 호출된다.
callback에 sendIntent등을 사용해서 간단히 타모듈에 전달할 수 있을 것이다.

// Import시킬 class
android.media.MediaPlayer.OnCompletionListener;

//사용 코드 예제
   mMediaplayer.setOnCompletionListener(new OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    Log.i("The Playing music is Completed.");

                    mMusicControlMgr.sendIntent(PlayControlMgr.PLAYING_COMPLETED);
                }
   });

저의 경우 BG로 MediaPlayer 제어를 하고, onCompletion이 호출되는 경우 intent를
Activity로 전달하여 처리하도록 구성했습니다.


2. 에러 발생시 상태 알수 있는 방법  

public void setOnErrorListener (MediaPlayer.OnErrorListener listener)

Since: API Level 1

Register a callback to be invoked when an error has happened during an asynchronous operation.

Parameters
listener the callback that will be run

//사용 예제 코드

           mMediaplayer.setOnErrorListener(new OnErrorListener() {
                public boolean onError(MediaPlayer mp, int what, int extra) {
                 Log("Error what : "+ what+" extra : "+extra);
                    cleanupPlayer();
                    mMusicControlMgr.sendIntent(PlayControlMgr.PLAYING_FAILED);
                    return true;
                }
            }); 

반응형