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.android.onemedia.playback.LocalRenderer.java

private boolean preparePlayer(final MediaPlayer player, boolean current) {
    player.setOnPreparedListener(this);
    player.setOnBufferingUpdateListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    try {/*from   w  ww  .j a va 2 s. c  o m*/
        player.prepareAsync();
        if (current) {
            setState(STATE_PREPARING);
        }
    } catch (IllegalStateException e) {
        if (current) {
            setError(Listener.ERROR_PREPARE_ERROR, 0, null, e);
        }
        return false;
    }
    return true;
}

From source file:com.yohpapa.research.simplemusicplayer.PlaybackService.java

private MediaPlayer initializePlayer() {
    MediaPlayer player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    player.setOnSeekCompleteListener(this);
    player.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);

    IntentFilter filter = new IntentFilter();
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    registerReceiver(audioOutputChangedEventReceiver, filter);

    return player;
}

From source file:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java

@Override
public void onCreate() {
    Util.setUncaughtExceptionHandler(this);
    super.onCreate();

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

    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override/*from   w ww . ja  v a  2  s  . c  om*/
        public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
            handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
            return false;
        }
    });

    if (equalizerAvailable) {
        equalizerController = new EqualizerController(this, mediaPlayer);
        if (!equalizerController.isAvailable()) {
            equalizerController = null;
        } else {
            equalizerController.loadSettings();
        }
    }
    if (visualizerAvailable) {
        visualizerController = new VisualizerController(this, mediaPlayer);
        if (!visualizerController.isAvailable()) {
            visualizerController = null;
        }
    }

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

    instance = this;
    lifecycleSupport.onCreate();
}

From source file:com.bayapps.android.robophish.playback.LocalPlayback.java

/**
 * Makes sure the media player exists and has been reset. This will create
 * the media player if needed, or reset the existing media player if one
 * already exists./*from w  w  w.  j  av  a  2 s.co  m*/
 */
private MediaPlayer createMediaPlayer(MediaPlayer player) {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (player == null));
    if (player == null) {
        player = new MediaPlayer();

        // Make sure the media player will acquire a wake-lock while
        // playing. If we don't do that, the CPU might go to sleep while the
        // song is playing, causing playback to stop.
        player.setWakeMode(mContext.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // we want the media player to notify us when it's ready preparing,
        // and when it's done playing:
        player.setOnPreparedListener(this);
        player.setOnCompletionListener(this);
        player.setOnErrorListener(this);
        player.setOnSeekCompleteListener(this);
    } else {
        player.reset();
    }

    return player;
}

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

private void setupHandlers(final DownloadFile downloadFile, final boolean isPartial) {
    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 = cachedPosition;
            reset();/*w  ww .  ja v a2s.  co  m*/
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000))) {
                playNext();
            } else {
                downloadFile.setPlaying(false);
                doPlay(downloadFile, pos, true);
                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(60000);

            setPlayerStateCompleted();

            int pos = cachedPosition;
            Log.i(TAG, "Ending position " + pos + " of " + duration);
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000))) {
                playNext();
                return;
            }

            // If file is not completely downloaded, restart the playback from the current position.
            synchronized (DownloadServiceImpl.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);
                    bufferTask.start();
                }
            }
        }
    });
}

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

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

    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/* w  w w.j  ava 2s.  com*/

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

            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, mediaPlayer.getAudioSessionId());
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).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);

    SharedPreferences prefs = Util.getPreferences(this);
    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);

    instance = this;
    lifecycleSupport.onCreate();

    if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
        getEqualizerController();
    }
}

From source file:se.eliga.aves.songs.BirdSpeciesXenoCantoPlayerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.audio_player_layout, container, false);

    setHasOptionsMenu(true);/* w w  w. j  av a  2s  .  co  m*/

    mediaPlayer = new MediaPlayer();
    mediaController = new MediaController(getActivity(), false);
    mediaController.setMediaPlayer(this);
    mediaController.setAnchorView(view);

    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            if (what == -38) {
                return true; //not pretty.. http://stackoverflow.com/questions/15205855/error-19-0-mediaplayer/15206308#15206308
            } else {
                return false;
            }
        }
    });

    mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            progressBar.setProgress(percent);
        }
    });
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            handler.post(new Runnable() {
                public void run() {
                    progressBar.setVisibility(ProgressBar.GONE);
                    if (mediaController != null) {
                        mediaController.show(0);
                    }
                    if (mediaPlayer != null) {
                        try {
                            mediaPlayer.start();
                        } catch (Exception e) {
                            Log.d(TAG, "Could not start mediaplayer", e);
                        }
                    }
                }
            });
        }
    });
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            if (audioAutoNext.isChecked()) {
                int count = getListAdapter().getCount();
                XenoCantoAudio nextAudio;
                if (currentPosition < (count - 1)) {
                    nextAudio = (XenoCantoAudio) getListAdapter().getItem(++currentPosition);
                } else {
                    nextAudio = (XenoCantoAudio) getListAdapter().getItem(0);
                }
                initiatePlay(nextAudio);
            }
        }
    });
    loadBird(getCurrentBird());
    return view;
}

From source file:org.botlibre.sdk.activity.ChatActivity.java

public MediaPlayer playAudio(String audio, boolean loop, boolean cache, boolean start) {
    try {//from w  ww .  j a v a  2 s  .co m
        Uri audioUri = null;
        if (cache) {
            audioUri = HttpGetVideoAction.fetchVideo(this, audio);
        }
        if (audioUri == null) {
            audioUri = Uri.parse(MainActivity.connection.fetchImage(audio).toURI().toString());
        }
        final MediaPlayer audioPlayer = new MediaPlayer();
        audioPlayer.setDataSource(getApplicationContext(), audioUri);
        audioPlayer.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.wtf("Audio error", "what:" + what + " extra:" + extra);
                audioPlayer.stop();
                audioPlayer.release();
                return true;
            }
        });
        audioPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                audioPlayer.release();
                runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            beginListening();
                        } catch (Exception e) {
                            Log.e("ChatActivity", "MediaPlayer: " + e.getMessage());
                        }
                    }
                });
            }
        });
        audioPlayer.prepare();
        audioPlayer.setLooping(loop);
        if (start) {
            audioPlayer.start();
        }
        return audioPlayer;
    } catch (Exception exception) {
        Log.wtf(exception.toString(), exception);
        return null;
    }
}

From source file:org.moire.ultrasonic.service.DownloadServiceImpl.java

private void setupHandlers(final DownloadFile downloadFile, final boolean isPartial) {
    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override//from  ww w. ja va  2  s.  c  o  m
        public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
            Log.w(TAG, String.format("Error on playing file (%d, %d): %s", what, extra, downloadFile));
            int pos = cachedPosition;
            reset();
            downloadFile.setPlaying(false);
            doPlay(downloadFile, pos, true);
            downloadFile.setPlaying(true);
            return true;
        }
    });

    final int duration = downloadFile.getSong().getDuration() == null ? 0
            : downloadFile.getSong().getDuration() * 1000;

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

            int pos = cachedPosition;
            Log.i(TAG, String.format("Ending position %d of %d", pos, duration));

            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 1000))) {
                setPlayerStateCompleted();

                if (Util.getGaplessPlaybackPreference(DownloadServiceImpl.this) && nextPlaying != null
                        && nextPlayerState == PlayerState.PREPARED) {
                    if (!nextSetup) {
                        playNext();
                    } else {
                        nextSetup = false;
                        playNext();
                    }
                } else {
                    onSongCompleted();
                }

                return;
            }

            synchronized (DownloadServiceImpl.this) {
                if (downloadFile.isWorkDone()) {
                    // Complete was called early even though file is fully buffered
                    Log.i(TAG, String.format("Requesting restart from %d of %d", pos, duration));
                    reset();
                    downloadFile.setPlaying(false);
                    doPlay(downloadFile, pos, true);
                    downloadFile.setPlaying(true);
                } else {
                    Log.i(TAG, String.format("Requesting restart from %d of %d", pos, duration));
                    reset();
                    bufferTask = new BufferTask(downloadFile, pos);
                    bufferTask.start();
                }
            }
        }
    });
}

From source file:org.moire.ultrasonic.service.DownloadServiceImpl.java

@SuppressLint("NewApi")
@Override//from w  w w. jav a2 s  . c om
public void onCreate() {
    super.onCreate();

    new Thread(new Runnable() {
        @Override
        public void run() {
            Thread.currentThread().setName("DownloadServiceImpl");

            Looper.prepare();

            if (mediaPlayer != null) {
                mediaPlayer.release();
            }

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

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

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

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).start();

    audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    setUpRemoteControlClient();

    if (equalizerAvailable) {
        equalizerController = new EqualizerController(this, mediaPlayer);
        if (!equalizerController.isAvailable()) {
            equalizerController = null;
        } else {
            equalizerController.loadSettings();
        }
    }
    if (visualizerAvailable) {
        visualizerController = new VisualizerController(mediaPlayer);
        if (!visualizerController.isAvailable()) {
            visualizerController = null;
        }
    }

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

    instance = this;
    lifecycleSupport.onCreate();
}