Example usage for android.media MediaPlayer setOnErrorListener

List of usage examples for android.media MediaPlayer setOnErrorListener

Introduction

In this page you can find the example usage for android.media MediaPlayer setOnErrorListener.

Prototype

public void setOnErrorListener(OnErrorListener listener) 

Source Link

Document

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

Usage

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

protected void initializePlayer(MediaPlayer player) {
    if (LOCAL_LOGV)
        log("initializePlayer()", "v");
    player.setOnPreparedListener(this);
    player.setOnInfoListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    //player.setOnBufferingUpdateListener(this);
    return;//w w w  .java2s  .  c  o  m
}

From source file:mp.teardrop.PlaybackService.java

/**
 * Returns a new MediaPlayer object/*  www .  j  a  va 2s.c om*/
 */
private MediaPlayer getNewMediaPlayer() {
    MediaPlayer mp = new MediaPlayer();
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mp.setOnCompletionListener(this);
    mp.setOnErrorListener(this);
    mp.setOnPreparedListener(this);
    return mp;
}

From source file:github.daneren2005.dsub.service.DownloadService.java

private void setupHandlers(final DownloadFile downloadFile, final boolean isPartial, final boolean isPlaying) {
    final int duration = downloadFile.getSong().getDuration() == null ? 0
            : downloadFile.getSong().getDuration() * 1000;
    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
            Log.w(TAG, "Error on playing file " + "(" + what + ", " + extra + "): " + downloadFile);
            int pos = getPlayerPosition();
            reset();/*from ww  w  .  j  av  a 2s  . c  om*/
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000))) {
                playNext();
            } else {
                downloadFile.setPlaying(false);
                doPlay(downloadFile, pos, isPlaying);
                downloadFile.setPlaying(true);
            }
            return true;
        }
    });

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            // Acquire a temporary wakelock, since when we return from
            // this callback the MediaPlayer will release its wakelock
            // and allow the device to go to sleep.
            wakeLock.acquire(30000);

            setPlayerStateCompleted();

            int pos = getPlayerPosition();
            Log.i(TAG, "Ending position " + pos + " of " + duration);
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000)) || nextSetup) {
                playNext();
                postPlayCleanup(downloadFile);
            } else {
                // If file is not completely downloaded, restart the playback from the current position.
                synchronized (DownloadService.this) {
                    if (downloadFile.isWorkDone()) {
                        // Complete was called early even though file is fully buffered
                        Log.i(TAG, "Requesting restart from " + pos + " of " + duration);
                        reset();
                        downloadFile.setPlaying(false);
                        doPlay(downloadFile, pos, true);
                        downloadFile.setPlaying(true);
                    } else {
                        Log.i(TAG, "Requesting restart from " + pos + " of " + duration);
                        reset();
                        bufferTask = new BufferTask(downloadFile, pos, true);
                        bufferTask.execute();
                    }
                }
                checkDownloads();
            }
        }
    });
}

From source file:github.daneren2005.dsub.service.DownloadService.java

@Override
public void onCreate() {
    super.onCreate();

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/*w ww  . j a v  a 2 s.co m*/

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            audioSessionId = -1;
            Integer id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            if (id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();
                    prefs.edit().putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId).commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientHelper.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();
}

From source file:github.popeen.dsub.service.DownloadService.java

private void setupHandlers(final DownloadFile downloadFile, final boolean isPartial, final boolean isPlaying) {
    final int duration = downloadFile.getSong().getDuration() == null ? 0
            : downloadFile.getSong().getDuration() * 1000;
    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
            Log.w(TAG, "Error on playing file " + "(" + what + ", " + extra + "): " + downloadFile);
            int pos = getPlayerPosition();
            reset();/*from ww  w .j a  v  a2 s  .com*/
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000))) {
                playNext();
            } else {
                downloadFile.setPlaying(false);
                doPlay(downloadFile, pos, isPlaying);
                downloadFile.setPlaying(true);
            }
            return true;
        }
    });

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            setPlayerStateCompleted();

            int pos = getPlayerPosition();
            Log.i(TAG, "Ending position " + pos + " of " + duration);
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000)) || nextSetup) {
                playNext();
                postPlayCleanup(downloadFile);
            } else {
                // If file is not completely downloaded, restart the playback from the current position.
                synchronized (DownloadService.this) {
                    if (downloadFile.isWorkDone()) {
                        // Complete was called early even though file is fully buffered
                        Log.i(TAG, "Requesting restart from " + pos + " of " + duration);
                        reset();
                        downloadFile.setPlaying(false);
                        doPlay(downloadFile, pos, true);
                        downloadFile.setPlaying(true);
                    } else {
                        Log.i(TAG, "Requesting restart from " + pos + " of " + duration);
                        reset();
                        bufferTask = new BufferTask(downloadFile, pos, true);
                        bufferTask.execute();
                    }
                }
                checkDownloads();
            }
        }
    });
}

From source file:github.popeen.dsub.service.DownloadService.java

@Override
public void onCreate() {
    super.onCreate();

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();//ww  w.j a  va 2s . co m

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            // We want to change audio session id's between upgrading Android versions.  Upgrading to Android 7.0 is broken (probably updated session id format)
            audioSessionId = -1;
            int id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            int versionCode = prefs.getInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, -1);
            if (versionCode == Build.VERSION.SDK_INT && id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    Log.w(TAG, "Failed to use cached audio session", e);
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();

                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId);
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, Build.VERSION.SDK_INT);
                    editor.commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            /*try {
               Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
               i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
               i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
               sendBroadcast(i);
            } catch(Throwable e) {
               // Froyo or lower
            }*/

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);
    audioNoisyReceiver = new AudioNoisyReceiver();
    registerReceiver(audioNoisyReceiver, audioNoisyIntent);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientBase.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "downloadServiceLock");

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();

    if (Build.VERSION.SDK_INT >= 26) {
        Notifications.shutGoogleUpNotification(this);
    }
}

From source file:github.daneren2005.dsub.service.DownloadService.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {//www.  jav a2  s .co  m
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        boolean isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        String dataSource = file.getAbsolutePath();
        if (isPartial && !Util.isOffline(this)) {
            if (proxy == null) {
                proxy = new BufferProxy(this);
                proxy.start();
            }
            proxy.setBufferFile(downloadFile);
            dataSource = proxy.getPrivateAddress(dataSource);
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}

From source file:github.popeen.dsub.service.DownloadService.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {/*from  w  ww .  j  av  a  2 s. c  o  m*/
        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }

        String dataSource;
        boolean isPartial = false;
        if (downloadFile.isStream()) {
            dataSource = downloadFile.getStream();
            Log.i(TAG, "Data Source: " + dataSource);
        } else {
            downloadFile.setPlaying(true);
            final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                    : downloadFile.getPartialFile();
            isPartial = file.equals(downloadFile.getPartialFile());
            downloadFile.updateModificationDate();

            dataSource = file.getAbsolutePath();
            if (isPartial && !Util.isOffline(this)) {
                if (proxy == null) {
                    proxy = new BufferProxy(this);
                    proxy.start();
                }
                proxy.setBufferFile(downloadFile);
                dataSource = proxy.getPrivateAddress(dataSource);
                Log.i(TAG, "Data Source: " + dataSource);
            } else if (proxy != null) {
                proxy.stop();
                proxy = null;
            }
        }

        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            applyPlaybackParamsMain();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }

                        updateRemotePlaylist();
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}