Example usage for android.media MediaPlayer release

List of usage examples for android.media MediaPlayer release

Introduction

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

Prototype

public void release() 

Source Link

Document

Releases resources associated with this MediaPlayer object.

Usage

From source file:it.interfree.leonardoce.bootreceiver.AlarmKlaxon.java

private void play() {
    // stop() checks to see if we are already playing.
    stop();//from   w  ww.j  ava 2  s .co  m

    if (LOGV) {
        Log.v(LTAG, "AlarmKlaxon.play() ");
    }

    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    if (LOGV) {
        Log.v(LTAG, "Using default alarm: " + alert.toString());
    }

    // TODO: Reuse mMediaPlayer instead of creating a new one and/or use
    // RingtoneManager.
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setOnErrorListener(new OnErrorListener() {
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.e(LTAG, "Error occurred while playing audio.");
            mp.stop();
            mp.release();
            mMediaPlayer = null;
            return true;
        }
    });

    try {
        // Check if we are in a call. If we are, use the in-call alarm
        // resource at a low volume to not disrupt the call.
        mMediaPlayer.setDataSource(this, alert);
        startAlarm(mMediaPlayer);
    } catch (Exception ex) {
        Log.v(LTAG, "Non trovo la suoneria dell'allarme???");
    }

    /* Start the vibrator after everything is ok with the media player */
    mVibrator.vibrate(sVibratePattern, 0);
    mPlaying = true;
    mStartTime = System.currentTimeMillis();
    enableKiller();
}

From source file:com.meiste.tempalarm.ui.Alarm.java

@Override
protected void onResume() {
    super.onResume();

    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    // do not play alarms if stream volume is 0 (typically because ringer mode is silent).
    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
        final Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(final MediaPlayer mp, final int what, final int extra) {
                Timber.e("Error occurred while playing audio.");
                mp.stop();//  w  ww.  j a v  a2s.co  m
                mp.reset();
                mp.release();
                mMediaPlayer = null;
                return true;
            }
        });
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        try {
            mMediaPlayer.setDataSource(this, alert);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (final IOException e) {
            Timber.e("Failed to play alarm tone: %s", e);
        }
    }

    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    mVibrator.vibrate(sVibratePattern, 0);

    mPlaying = true;
    mHandler.sendEmptyMessageDelayed(KILLER, ALARM_TIMEOUT);
}

From source file:com.jungle.base.utils.MiscUtils.java

public static void playSound(Context context, int soundResId) {
    final MediaPlayer player = MediaPlayer.create(context, soundResId);
    if (player == null) {
        return;/*from  www . j a v  a2  s.  c  o  m*/
    }

    AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    int maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    int currVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);

    float volume = 1.0f;
    if (maxVolume > 0) {
        volume = (float) currVolume / (float) maxVolume;
    }

    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            player.release();
        }
    });

    player.setVolume(volume, volume);
    player.start();
}

From source file:com.joshmoles.byobcontroller.ControlActivity.java

/**
 * Plays raw game audio provided a resource location.
 * @param resource The android resource ID of audio to play.
 *//*from w  w  w .j  a va  2  s  . co  m*/
private void playAudio(int resource) {
    MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), resource);
    mediaPlayer.start();
    while (mediaPlayer.isPlaying())
        android.os.SystemClock.sleep(1000);
    mediaPlayer.release();
    Log.v(Consts.LOAD_FETCH, "Audio released");
}

From source file:me.tylerbwong.pokebase.gui.activities.PokemonProfileActivity.java

private void playAudio() {
    final MediaPlayer player = MediaPlayer.create(this,
            getResources().getIdentifier(AUDIO + pokemonId, RAW, getPackageName()));
    player.setOnCompletionListener(mediaPlayer -> player.release());
    player.start();/*w  w  w. j  ava  2  s. c  o  m*/
    Toast.makeText(this, getString(R.string.sound_played), Toast.LENGTH_SHORT).show();
}

From source file:net.potterpcs.recipebook.TimerFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    startButton = (Button) getActivity().findViewById(R.id.timerstartbutton);
    stopButton = (Button) getActivity().findViewById(R.id.timerstopbutton);
    display = (TextView) getActivity().findViewById(R.id.timerdisplay);
    minutePicker = (NumberPicker) getActivity().findViewById(R.id.minutepicker);
    secondPicker = (NumberPicker) getActivity().findViewById(R.id.secondpicker);
    timermin = (EditText) getActivity().findViewById(R.id.timerdisplayminutes);
    timersec = (EditText) getActivity().findViewById(R.id.timerdisplayseconds);

    if (minutePicker != null) {
        minutePicker.setMinValue(0);//from   ww  w . j  av a2s .c  o  m
        minutePicker.setMaxValue(99);
        secondPicker.setMinValue(0);
        secondPicker.setMaxValue(59);
        secondPicker.setFormatter(new Formatter() {
            @Override
            public String format(int value) {
                return String.format("%02d", value);
            }
        });
        getActivity().findViewById(R.id.pickerlayout).setVisibility(View.VISIBLE);
        display.setVisibility(View.GONE);
    }

    startButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            int seconds;
            if (minutePicker != null) {
                seconds = minutePicker.getValue() * 60 + secondPicker.getValue();
            } else {
                int m = Integer.parseInt(timermin.getEditableText().toString());
                int s = Integer.parseInt(timersec.getEditableText().toString());
                seconds = m * 60 + s;
                timermin.setText(timermin.getText(), BufferType.NORMAL);
                timersec.setText(timersec.getText(), BufferType.NORMAL);
            }
            startButton.setEnabled(false);
            stopButton.setEnabled(true);

            if (minutePicker == null) {
                timermin.setEnabled(false);
                timersec.setEnabled(false);
            } else {
                minutePicker.setEnabled(false);
                secondPicker.setEnabled(false);
                getActivity().findViewById(R.id.pickerlayout).setVisibility(View.GONE);
                display.setVisibility(View.VISIBLE);
            }

            if (display != null) {
                display.setText(DateUtils.formatElapsedTime(seconds));
            }

            timer = new CountDownTimer(seconds * 1000, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    //                  Log.i(TAG, "tick " + millisUntilFinished);
                    if (display != null) {
                        display.setText(DateUtils.formatElapsedTime(millisUntilFinished / 1000));
                    } else {
                        int totalsec = (int) (millisUntilFinished / 1000);
                        int s = totalsec % 60;
                        int m = totalsec / 60;
                        timermin.setText(String.format("%02d", m));
                        timersec.setText(String.format("%02d", s));
                    }
                }

                @Override
                public void onFinish() {
                    // Play a sound and show a message when the timer ends
                    MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.ding);
                    mp.setOnCompletionListener(new OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mp.release();
                        }
                    });
                    mp.setVolume(1.0f, 1.0f);
                    Toast.makeText(getActivity(), "Done!", Toast.LENGTH_LONG).show();
                    mp.start();
                    clearToZero();
                }
            };

            timer.start();
        }
    });

    stopButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            timer.cancel();
            clearToZero();
        }
    });
}

From source file:me.tipi.kiosk.ui.fragments.OCRFragment.java

/**
 * Plays beep sound.//w  w  w  .  j av a 2  s  .  co m
 */
private void soundNotification() {
    if (mMediaPlayer != null) {
        Log.d(TAG, "Playing beep sound");
        mMediaPlayer.start();
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                if (mMediaPlayer == null) {
                    mp.release();
                }
            }
        });
    }
}

From source file:com.google.dotorg.crisisresponse.translationcards.RecordingActivity.java

private void finishListening(MediaPlayer mediaPlayer) {
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.stop();/* w w w . j a  va  2 s .c  o m*/
    }
    mediaPlayer.reset();
    mediaPlayer.release();
    recordButton.setBackgroundResource(R.drawable.button_record_enabled);
    listenButton.setBackgroundResource(R.drawable.button_listen_enabled);
    recordingStatus = RecordingStatus.RECORDED;
}

From source file:org.yuttadhammo.BodhiTimer.TimerReceiver.java

@Override
public void onReceive(Context context, Intent pintent) {
    Log.v(TAG, "ALARM: received alarm");

    NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (player != null) {
        Log.v(TAG, "Releasing media player...");
        try {//from w  ww. j  av  a  2s .  co  m
            player.release();
            player = null;
        } catch (Exception e) {
            e.printStackTrace();
            player = null;
        } finally {
            // do nothing
        }
    }

    // Cancel notification and return...
    if (CANCEL_NOTIFICATION.equals(pintent.getAction())) {
        Log.v(TAG, "Cancelling notification...");

        mNM.cancelAll();
        return;
    }

    // ...or display a new one

    Log.v(TAG, "Showing notification...");

    player = new MediaPlayer();

    int setTime = pintent.getIntExtra("SetTime", 0);
    String setTimeStr = TimerUtils.time2humanStr(context, setTime);
    Log.v(TAG, "Time: " + setTime);

    CharSequence text = context.getText(R.string.Notification);
    CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr);

    // Load the settings 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean led = prefs.getBoolean("LED", true);
    boolean vibrate = prefs.getBoolean("Vibrate", true);
    String notificationUri = "";

    boolean useAdvTime = prefs.getBoolean("useAdvTime", false);
    String advTimeString = prefs.getString("advTimeString", "");
    String[] advTime = null;
    int advTimeIndex = 1;

    if (useAdvTime && advTimeString.length() > 0) {
        advTime = advTimeString.split("\\^");
        advTimeIndex = prefs.getInt("advTimeIndex", 1);
        String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound

        if (thisAdvTime.length == 3)
            notificationUri = thisAdvTime[1];
        if (notificationUri.equals("sys_def"))
            notificationUri = prefs.getString("NotificationUri",
                    "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);
    } else
        notificationUri = prefs.getString("NotificationUri",
                "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);

    Log.v(TAG, "notification uri: " + notificationUri);

    if (notificationUri.equals("system"))
        notificationUri = prefs.getString("SystemUri", "");
    else if (notificationUri.equals("file"))
        notificationUri = prefs.getString("FileUri", "");
    else if (notificationUri.equals("tts")) {
        notificationUri = "";
        final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done));
        Intent ttsIntent = new Intent(context, TTSService.class);
        ttsIntent.putExtra("spoken_text", ttsString);
        context.startService(ttsIntent);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext())
            .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest);

    Uri uri = null;

    // Play a sound!
    if (!notificationUri.equals(""))
        uri = Uri.parse(notificationUri);

    // Vibrate
    if (vibrate && uri == null) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    // Have a light
    if (led) {
        mBuilder.setLights(0xff00ff00, 300, 1000);
    }

    mBuilder.setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, TimerActivity.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(TimerActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Create intent for cancelling the notification
    Context appContext = context.getApplicationContext();
    Intent intent = new Intent(appContext, TimerReceiver.class);
    intent.setAction(CANCEL_NOTIFICATION);

    // Cancel the pending cancellation and create a new one
    PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    if (uri != null) {

        //remove notification sound
        mBuilder.setSound(null);

        try {
            if (player != null && player.isPlaying()) {
                player.release();
                player = new MediaPlayer();
            }

            int currVolume = prefs.getInt("tone_volume", 0);
            if (currVolume != 0) {
                float log1 = (float) (Math.log(100 - currVolume) / Math.log(100));
                player.setVolume(1 - log1, 1 - log1);
            }
            player.setDataSource(context, uri);
            player.prepare();
            player.setLooping(false);
            player.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mp.release();
                }

            });
            player.start();
            if (vibrate) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(1000);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("AutoClear", false)) {
        // Determine duration of notification sound
        int duration = 5000;
        if (uri != null) {
            MediaPlayer cancelPlayer = new MediaPlayer();
            try {
                cancelPlayer.setDataSource(context, uri);
                cancelPlayer.prepare();
                duration = Math.max(duration, cancelPlayer.getDuration() + 2000);
            } catch (java.io.IOException ex) {
                Log.e(TAG, "Cannot get sound duration: " + ex);
                duration = 30000; // on error, default to 30 seconds
            } finally {
                cancelPlayer.release();
            }
            cancelPlayer.release();
        }
        Log.v(TAG, "Notification duration: " + duration + " ms");
        // Schedule cancellation
        AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration,
                pendingCancelIntent);
    }

    if (useAdvTime && advTimeString.length() > 0) {
        Intent broadcast = new Intent();

        SharedPreferences.Editor editor = prefs.edit();
        if (advTimeIndex < advTime.length) {
            editor.putInt("advTimeIndex", advTimeIndex + 1);

            String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound

            int time = Integer.parseInt(thisAdvTime[0]);

            broadcast.putExtra("time", time);

            // Save new time
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);

            // editor.putString("NotificationUri", thisAdvTime[1]);

            mNM.cancelAll();
            Log.v(TAG, "Starting next iteration of the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);
        } else {
            broadcast.putExtra("stop", true);
            editor.putInt("advTimeIndex", 1);

        }
        broadcast.setAction(BROADCAST_RESET);
        context.sendBroadcast(broadcast);

        editor.apply();

    } else if (prefs.getBoolean("AutoRestart", false)) {
        int time = pintent.getIntExtra("SetTime", 0);
        if (time != 0) {

            mNM.cancel(0);
            Log.v(TAG, "Restarting the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);

            // Save new time
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);
            editor.apply();

            Intent broadcast = new Intent();
            broadcast.putExtra("time", time);
            broadcast.setAction(BROADCAST_RESET);
            context.sendBroadcast(broadcast);

        }
    }

    mNotificationManager.notify(0, mBuilder.build());

    Log.d(TAG, "ALARM: alarm finished");

}

From source file:com.android.onemedia.playback.LocalRenderer.java

private void cleanUpPlayer() {
    if (DEBUG) {/*  w ww  . j a va2s  .  c  o m*/
        Log.d(TAG, mDebugId + ": Cleaning up current player");
    }
    synchronized (mErrorLock) {
        mError = null;
        if (mErrorRetriever != null) {
            mErrorRetriever.cancelRequestLocked(false);
            // Don't set to null as we may need to cancel again with true if
            // the object gets destroyed.
        }
    }
    mAudioManager.abandonAudioFocus(this);

    SurfaceHolder.Callback cb = mHolderCB;
    mHolderCB = null;
    SurfaceHolder holder = mHolder;
    mHolder = null;
    if (holder != null && cb != null) {
        holder.removeCallback(cb);
    }

    MediaPlayer player = mPlayer;
    mPlayer = null;
    if (player != null) {
        player.reset();
        player.release();
    }
}