Java Code Examples for android.media.MediaPlayer#stop()

The following examples show how to use android.media.MediaPlayer#stop() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KcaUtils.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
public static void playNotificationSound(MediaPlayer mediaPlayer, Context context, Uri uri) {
    try {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
        if (uri != null && !Uri.EMPTY.equals(uri)) {
            mediaPlayer.setDataSource(context, uri);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                AudioAttributes attr = new AudioAttributes.Builder()
                        .setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
                        .build();
                mediaPlayer.setAudioAttributes(attr);
            } else {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            }
            mediaPlayer.prepare();
            mediaPlayer.start();
        }
    } catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: MusicService.java    From RhymeMusic with Apache License 2.0 6 votes vote down vote up
@Override
public void onCompletion(MediaPlayer mp)
{
    Log.d(TAG, SUB + "onCompletion");

    if ( application.isOnline() )
    {
        Toast.makeText(getBaseContext(), "因时间原因,该功能暂未实现。",
                Toast.LENGTH_LONG).show();
        mp.stop();
    }
    else
    {
        binder.nextTrack();
    }

}
 
Example 3
Source File: AlarmService.java    From sleep-cycle-alarm with GNU General Public License v3.0 6 votes vote down vote up
private void startPlayer() {
    player = new MediaPlayer();

    try {
        if (isVibrateEnabled()) {
            postVibrationHandler();
        }
        player.setDataSource(this, Uri.parse(alarmRingtone));
        player.setLooping(true);
        player.setAudioStreamType(AudioManager.STREAM_ALARM);
        player.setVolume(volumeLevel, volumeLevel);
        player.prepare();
        player.start();
        postDelayedVolumeHandler();
    } catch (Exception e) {
        if (player.isPlaying()) {
            player.stop();
        }
        Log.e(getClass().getName(), "startPlayer(): " + e.getMessage());
        stopSelf();
    }
}
 
Example 4
Source File: MainActivity.java    From astrobee_android with Apache License 2.0 6 votes vote down vote up
public void onPlayClick(View v) {
    if (!mPlaying) {
        try {
            mPlayer = new MediaPlayer();
            AssetFileDescriptor fd = getResources().openRawResourceFd(R.raw.astrobee);
            mPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            mPlayer.setOnCompletionListener(mOnCompletionListener);
            mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mPlayer.prepare();
            mPlayer.start();
            mPlaying = true;
            setState(STATE_PLAYING);
        } catch (IOException e) {
            Log.e(TAG, "error trying to play a sound");
        }
    } else {
        mPlayer.setOnCompletionListener(null);
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
        mPlaying = false;
        setState(STATE_IDLE);
    }
}
 
Example 5
Source File: LoveVideoView.java    From gank.io-unofficial-android-client with Apache License 2.0 5 votes vote down vote up
@Override
public void onCompletion(MediaPlayer player) {

  if (player != null) {
    if (player.isPlaying()) player.stop();
    player.reset();
    player.release();
    player = null;
  }
}
 
Example 6
Source File: AndroidAudioRenderer.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onCompletion(MediaPlayer mp) {
    for (AudioNode src : musicPlaying.keySet()) {
        if (musicPlaying.get(src) == mp) {
            mp.seekTo(0);
            mp.stop();
            src.setStatus(Status.Stopped);
            break;
        }
    }

}
 
Example 7
Source File: LoveVideoView.java    From gank with GNU General Public License v3.0 5 votes vote down vote up
@Override public void onCompletion(MediaPlayer player) {
    if (player != null) {
        if (player.isPlaying()) player.stop();
        player.reset();
        player.release();
        player = null;
    }
}
 
Example 8
Source File: BGMFader.java    From SchoolQuest with GNU General Public License v3.0 5 votes vote down vote up
public static void stop(final MediaPlayer mediaPlayer, int fadeDuration,
                        final Runnable... endRunnable) {
    if (fadeDuration > 0) { iVolume = INT_VOLUME_MAX; }
    else { iVolume = INT_VOLUME_MIN; }

    updateVolume(mediaPlayer, 0);

    if (fadeDuration > 0) {
        final Timer timer = new Timer(true);
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                updateVolume(mediaPlayer,-1);
                if (iVolume == INT_VOLUME_MIN) {
                    mediaPlayer.stop();
                    timer.cancel();
                    timer.purge();
                    if (endRunnable.length != 0) { endRunnable[0].run(); }
                }
            }
        };

        int delay = fadeDuration / INT_VOLUME_MAX;
        if (delay == 0) { delay = 1; }

        timer.schedule(timerTask, delay, delay);
    }
}
 
Example 9
Source File: AlarmService.java    From talalarmo with MIT License 5 votes vote down vote up
private void startPlayer() {
    mPlayer = new MediaPlayer();
    mPlayer.setOnErrorListener(mErrorListener);

    try {
        // add vibration to alarm alert if it is set
        if (App.getState().settings().vibrate()) {
            mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            mHandler.post(mVibrationRunnable);
        }
        // Player setup is here
        String ringtone = App.getState().settings().ringtone();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && ringtone.startsWith("content://media/external/")
                && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
        }
        mPlayer.setDataSource(this, Uri.parse(ringtone));
        mPlayer.setLooping(true);
        mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mPlayer.setVolume(mVolumeLevel, mVolumeLevel);
        mPlayer.prepare();
        mPlayer.start();

        if (App.getState().settings().ramping()) {
            mHandler.postDelayed(mVolumeRunnable, VOLUME_INCREASE_DELAY);
        } else {
            mPlayer.setVolume(MAX_VOLUME, MAX_VOLUME);
        }
    } catch (Exception e) {
        if (mPlayer.isPlaying()) {
            mPlayer.stop();
        }
        stopSelf();
    }
}
 
Example 10
Source File: Sound.java    From Tick with MIT License 5 votes vote down vote up
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
    mediaPlayer.stop();
    mediaPlayer.release();
    mMediaPlayer = mNextPlayer;
    setNextMediaPlayer();
}
 
Example 11
Source File: VideoPlayer.java    From cordova-plugin-videoplayer with MIT License 5 votes vote down vote up
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Log.e(LOG_TAG, "MediaPlayer.onError(" + what + ", " + extra + ")");
    if(mp.isPlaying()) {
        mp.stop();
    }
    mp.release();
    dialog.dismiss();
    return false;
}
 
Example 12
Source File: LocationAwareService.java    From LocationAware with Apache License 2.0 5 votes vote down vote up
private void startPlayer() {
  mPlayer = new MediaPlayer();
  mPlayer.setOnErrorListener(mErrorListener);

  try {
    isAlarmRinging = true;
    // add vibration to alarm alert if it is set
    //if (App.getState().settings().vibrate()) {
    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    mHandler.post(mVibrationRunnable);
    //}
    // Player setup is here
    String ringtone;// = App.getState().settings().ringtone();
    //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    //    && ringtone.startsWith("content://media/external/")
    //    && checkSelfPermission(
    //    Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
    ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
    //}
    mPlayer.setDataSource(this, Uri.parse(ringtone));
    mPlayer.setLooping(true);
    mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
    mPlayer.setVolume(mVolumeLevel, mVolumeLevel);
    mPlayer.prepare();
    mPlayer.start();

    //if (App.getState().settings().ramping()) {
    //  mHandler.postDelayed(mVolumeRunnable, VOLUME_INCREASE_DELAY);
    //} else {
    mPlayer.setVolume(MAX_VOLUME, MAX_VOLUME);
    //}
  } catch (Exception e) {
    isAlarmRinging = false;
    if (mPlayer.isPlaying()) {
      mPlayer.stop();
    }
    stopSelf();
  }
}
 
Example 13
Source File: Sound.java    From timecat with Apache License 2.0 5 votes vote down vote up
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
    mediaPlayer.stop();
    mediaPlayer.release();
    mMediaPlayer = mNextPlayer;
    setNextMediaPlayer();
}
 
Example 14
Source File: WebVideoPresenter.java    From Gank.io with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCompletion(MediaPlayer player) {
  if (player != null) {
    if (player.isPlaying()) player.stop();
    player.reset();
    player.release();
  }
}
 
Example 15
Source File: WearMessageListenerService.java    From AnkiDroid-Wear with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onCompletion(MediaPlayer mp) {
    mp.stop();
    mp.reset();
    startPlayingSounds();
}
 
Example 16
Source File: ChatAdapter.java    From FlyWoo with Apache License 2.0 4 votes vote down vote up
/**
 * 播放录音
 *
 * @param view
 * @param position
 */
private void OnClickVoice(View view, int position) {

    // 播放录音
    final ImageView iv_voice = (ImageView) view
            .findViewById(R.id.iv_voice);
    final ChatEntity item = list.get(position);
    if (!isPlay) {
        mMediaPlayer = new MediaPlayer();
        String filePath = item.getContent();
        try {
            mMediaPlayer.setDataSource(filePath);
            mMediaPlayer.prepare();
            startRecordAnimation(item, iv_voice);
            isPlay = true;
            mMediaPlayer.start();
            // 设置播放结束时监听
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (isPlay) {
                        stopRecordAnimation(item, iv_voice);
                        isPlay = false;
                        mMediaPlayer.stop();
                        mMediaPlayer.release();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            isPlay = false;
        } else {
            isPlay = false;
            mMediaPlayer.release();
        }
        stopRecordAnimation(item, iv_voice);
    }

}
 
Example 17
Source File: MainService.java    From android-play-games-in-motion with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
    // The service is being created.
    Utils.logDebug(TAG, "onCreate");
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_1);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_2);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_3);
    registerReceiver(mReceiver, intentFilter);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Determines the behavior for handling Audio Focus surrender.
    mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                    || focusChange == AudioManager.AUDIOFOCUS_LOSS) {

                if (mTextToSpeech.isSpeaking()) {
                    mTextToSpeech.setOnUtteranceProgressListener(null);
                    mTextToSpeech.stop();
                }

                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                }

                // Abandon Audio Focus, if it's requested elsewhere.
                mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);

                // Restart the current moment if AudioFocus was lost. Since AudioFocus is only
                // requested away from this application if this application was using it,
                // only Moments that play sound will restart in this way.
                if (mMission != null) {
                    mMission.restartMoment();
                }
            }
        }
    };

    // Asynchronously prepares the TextToSpeech.
    mTextToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                // Check if language is available.
                switch (mTextToSpeech.isLanguageAvailable(DEFAULT_TEXT_TO_SPEECH_LOCALE)) {
                    case TextToSpeech.LANG_AVAILABLE:
                    case TextToSpeech.LANG_COUNTRY_AVAILABLE:
                    case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
                        Utils.logDebug(TAG, "TTS locale supported.");
                        mTextToSpeech.setLanguage(DEFAULT_TEXT_TO_SPEECH_LOCALE);
                        mIsTextToSpeechReady = true;
                        break;
                    case TextToSpeech.LANG_MISSING_DATA:
                        Utils.logDebug(TAG, "TTS missing data, ask for install.");
                        Intent installIntent = new Intent();
                        installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                        startActivity(installIntent);
                        break;
                    default:
                        Utils.logDebug(TAG, "TTS local not supported.");
                        break;
                }
            }
        }
    });

    mMediaPlayer = new MediaPlayer();
}
 
Example 18
Source File: OnlinePlayer.java    From RhymeMusic with Apache License 2.0 4 votes vote down vote up
@Override
public boolean onError(MediaPlayer mp, int what, int extra)
{
    mp.stop();
    return false;
}
 
Example 19
Source File: OnlinePlayer.java    From RhymeMusic with Apache License 2.0 4 votes vote down vote up
@Override
public void onCompletion(MediaPlayer mp)
{
    mp.stop();
}
 
Example 20
Source File: ChatActivity.java    From WifiChat with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // TODO Auto-generated method stub
    Message msg = mMessagesList.get((int) id);
    switch (msg.getContentType()) {
        case IMAGE:
            Intent imgIntent = new Intent(mContext, ImageBrowserActivity.class);
            imgIntent
                    .putExtra(ImageBrowserActivity.IMAGE_TYPE, ImageBrowserActivity.TYPE_PHOTO);
            imgIntent.putExtra(ImageBrowserActivity.PATH, msg.getMsgContent());
            startActivity(imgIntent);
            overridePendingTransition(R.anim.zoom_enter, 0);

            break;

        case VOICE:
            // 播放录音
            final ImageView imgView = (ImageView) view
                    .findViewById(R.id.voice_message_iv_msgimage);
            if (!isPlay) {
                mMediaPlayer = new MediaPlayer();
                String filePath = msg.getMsgContent();
                try {
                    mMediaPlayer.setDataSource(filePath);
                    mMediaPlayer.prepare();
                    imgView.setImageResource(R.drawable.voicerecord_stop);
                    isPlay = true;
                    mMediaPlayer.start();
                    // 设置播放结束时监听
                    mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            if (isPlay) {
                                imgView.setImageResource(R.drawable.voicerecord_right);
                                isPlay = false;
                                mMediaPlayer.stop();
                                mMediaPlayer.release();
                            }
                        }
                    });
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            else {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                    mMediaPlayer.release();
                    isPlay = false;
                }
                else {
                    isPlay = false;
                    mMediaPlayer.release();
                }
                imgView.setImageResource(R.drawable.voicerecord_right);
            }

            break;

        case FILE:
            Intent fileIntent = new Intent();
            fileIntent.setType("*/*");
            fileIntent.setData(Uri.parse("file://"
                    + FileUtils.getPathByFullPath(msg.getMsgContent())));
            mContext.startActivity(fileIntent);
            break;

        default:
            break;

    }

}