暂停后MediaPlayer无法恢复

时间:2015-08-01 11:23:31

标签: android android-mediaplayer

我有一个MediaStreamerService来处理我的媒体播放器任务, 它没问题但是一旦Resume()被调用它就会面临错误,它在调用Pause()后无法恢复。在logcat中我看到Stop()被调用,没有任何异常或错误。 这是我的班级:

public class MediaStreamerService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener, AudioManager.OnAudioFocusChangeListener{


    public static final int AUDIO_FOCUS_DENIED_ERROR = 0;
    public static final int MEDIA_PLAYER_ERROR = 1;

    public static final int NOTIFICATION_ID = 1;


    private static MediaPlayer mMediaPlayer;
    private static boolean isPlaying = false;
    private static boolean isPaused = false;
    private static boolean isPreparing = false;
    private static boolean isStreamError = false;

    private static String urlToStream = "";
    private static String url = "";
    private static String title = "";
    private static String image = "";
    private static int length = 0;

    private static boolean isRunning = false;

    private BroadcastReceiver audioTooNoisyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            stop();
        }
    };
    @Override
    public void onCreate() {
        Log.i(TAG, "MediaStreamerService.onCreate()");

        isPlaying = false;
        isRunning = true;

        IntentFilter inf = new IntentFilter();
        inf.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
        inf.addAction(PLAYBACK_TIMEOUT_INTENT);

        registerReceiver(audioTooNoisyReceiver, inf);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // No intent, tell the system not to restart us.
        if (intent == null) {
            stopSelf();
            return START_STICKY;
        }

        if(intent.getAction() == PLAY_INTENT){
            Log.i(TAG, "MediaStreamerService.onStartCommand() - Received play intent");

            stop();

            urlToStream = intent.getStringExtra(URL_EXTRA);
            if(urlToStream == null)
                urlToStream = "";

            title = intent.getStringExtra(TITLE_EXTRA);
            if(title == null)
                title = "";

            image = intent.getStringExtra(IMAGE_EXTRA);
            if(image == null)
                image = "";

            url = intent.getStringExtra(TAG_URL);
            if(url == null)
                url = "";


            play();
        }
        else if(intent.getAction() == STOP_INTENT){    
            stop();
        }
        else if(intent.getAction() == CANCEL_PLAYBACK_INTENT){    
            stop();
            sendBroadcast(new Intent(STOPPED_PLAYBACK_INTENT));
        }
        else if(intent.getAction() == KILL_SERVICE_INTENT){

            stopSelf();
        }
        else if(intent.getAction() == RESUME_INTENT){

            resume();
        }
        else if(intent.getAction() == PAUSE_INTENT){

            pause();
        }

        return START_STICKY;
    }

    private void play(){    
        isPreparing = true;
        startNotification();

        if(!requestAudioFocus()){

            notifyStreamError(AUDIO_FOCUS_DENIED_ERROR);
        }

        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnPreparedListener(this);

        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setVolume(1.0f, 1.0f);
        try {
            mMediaPlayer.setDataSource(this, Uri.parse(urlToStream));
        } catch (Exception e){

            stop();
            notifyStreamError(MEDIA_PLAYER_ERROR);
            return;
        }
        try{
            mMediaPlayer.prepareAsync(); // prepare async to not block main thread
        } catch (Exception e){
            Log.e(TAG, "MediaStreamerService.play() - Error preparing the media player", e);
            stop();
            notifyStreamError(MEDIA_PLAYER_ERROR);
            return;
        }

    }

    private void resume() {
        Log.i(TAG, "MediaStreamerService.resume()");

        isPreparing = true;
        startNotification();

        if(!requestAudioFocus()){
            Log.i(TAG, "MediaStreamerService.resume() - AudioFocus request denied");

            notifyStreamError(AUDIO_FOCUS_DENIED_ERROR);
        }
        try {
            mMediaPlayer.seekTo(length);
            mMediaPlayer.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }

    }

    private boolean requestAudioFocus(){
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

        if(result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
            return false;
        else
            return true;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        try{
            mMediaPlayer.start();
            isPreparing = false;
        } catch (Exception e){
            Log.e(TAG, "MediaStreamerService.play() - onPreparedProxy - Error starting the media player", e);
            stop();
            notifyStreamError(MEDIA_PLAYER_ERROR);
            return;
        }

        isPlaying = true;
        notifyClearStreamError();

        sendBroadcast(new Intent(STARTED_PLAYBACK_INTENT));
    }



    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        Log.e(TAG, "Error occurred while playing audio. What = " + what + " - Extra = " + extra);
        isPreparing = false;
        stop();
        notifyStreamError(MEDIA_PLAYER_ERROR);
        startNotification();
        return false;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        stop();
    }

     void pause(){
        Log.i(TAG, "MediaStreamerService.pause() - Just dropping by");
        if(isPlaying)
            isPlaying = false;

        isPaused = true;

        isPreparing = false;

        if (mMediaPlayer != null) {
            try{
                if(mMediaPlayer.isPlaying()){
                    Log.i(TAG, "MediaStreamerService.pause() - Pausing media player" + mMediaPlayer.getCurrentPosition());
                    length = mMediaPlayer.getCurrentPosition();
                    mMediaPlayer.pause();
                    sendBroadcast(new Intent(PAUSED_PLAYBACK_INTENT));
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                    boolean persistentNotification = prefs.getBoolean(getString(R.string.pref_notification_key), Boolean.parseBoolean(getString(R.string.pref_notification_default)));
                    if(persistentNotification)
                        startNotification();
                    else
                        stopNotification();
                }
            }
            catch(Exception e){
                Log.e(TAG, "MediaStreamerService.pause() - Error while attempting to pause media player - ", e);
            }
            /*try{
                Log.i(TAG, "MediaStreamerService.pause() - Releasing media player");
                mMediaPlayer.release();
            }
            catch(Exception e){
                Log.e(TAG, "MediaStreamerService.pause() - Error while attempting to release media player - ", e);
            }
            Log.i(TAG, "MediaStreamerService.pause() - mMediaPlayer = null");
            mMediaPlayer = null;*/
        }
    }

    /*package*/ void stop(){
        Log.i(TAG, "MediaStreamerService.stop() - Just dropping by");
        if(isPlaying)
            isPlaying = false;

        isPreparing = false;

        if (mMediaPlayer != null) {
            try{
                if(mMediaPlayer.isPlaying()){
                    Log.i(TAG, "MediaStreamerService.stop() - Stopping media player");
                    mMediaPlayer.stop();
                    sendBroadcast(new Intent(STOPPED_PLAYBACK_INTENT));
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                    boolean persistentNotification = prefs.getBoolean(getString(R.string.pref_notification_key), Boolean.parseBoolean(getString(R.string.pref_notification_default)));
                    if(persistentNotification)
                        startNotification();
                    else
                        stopNotification();
                }
            }
            catch(Exception e){
                Log.e(TAG, "MediaStreamerService.stop() - Error while attempting to stop media player - ", e);
            }
            try{
                Log.i(TAG, "MediaStreamerService.stop() - Releasing media player");
                mMediaPlayer.release();
            }
            catch(Exception e){
                Log.e(TAG, "MediaStreamerService.stop() - Error while attempting to release media player - ", e);
            }
            Log.i(TAG, "MediaStreamerService.stop() - mMediaPlayer = null");
            mMediaPlayer = null;
        }
    }

    private void notifyStreamError(int error){
        isStreamError = true;
        Intent i = new Intent(ERROR_INTENT);
        i.putExtra(ERROR_EXTRA, error);
        sendBroadcast(i);
    }

    private void notifyClearStreamError(){
        if(isStreamError){
            isStreamError = false;
            sendBroadcast(new Intent(CLEAR_ERROR_INTENT));
        }
    }


    @Override
    public void onDestroy() {
        Log.i("UrlMediaStreamer", "MediaStreamerService.onDestroy()");
        stop();
        isRunning = false;
        if(mMediaPlayer != null)
            mMediaPlayer.release();

        unregisterReceiver(audioTooNoisyReceiver);

        stopNotification();

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            stop();
            play();
            break;

        case AudioManager.AUDIOFOCUS_LOSS:
            // Lost focus for an unbounded amount of time: stop playback and release media player
            stop();
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            // Lost focus for a short time, but we have to stop
            stop();
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            // Lost focus for a short time, but it's ok to keep playing
            // at an attenuated level
            stop();
            break;
    }

    }

}

1 个答案:

答案 0 :(得分:0)

暂停和恢复调用

raw/sphere_obj