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

The following examples show how to use android.media.MediaPlayer#isPlaying() . 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: ApplozicDocumentView.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void updateApplozicSeekBar() {
    MediaPlayer mediaplayer = ApplozicAudioManager.getInstance(context).getMediaPlayer(message.getKeyString());
    if (mediaplayer == null) {
        audioseekbar.setProgress(0);
    } else if (mediaplayer.isPlaying()) {
        audioseekbar.setMax(mediaplayer.getDuration());
        audioseekbar.setProgress(mediaplayer.getCurrentPosition());
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                updateApplozicSeekBar();
            }
        };
        mHandler.postDelayed(runnable, 500);
    } else {
        audioseekbar.setMax(mediaplayer.getDuration());
        audioseekbar.setProgress(mediaplayer.getCurrentPosition());
    }
}
 
Example 2
Source File: RNSoundModule.java    From react-native-sound with MIT License 6 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
  if (!this.mixWithOthers) {
    MediaPlayer player = this.playerPool.get(this.focusedPlayerKey);

    if (player != null) {
      if (focusChange <= 0) {
          this.wasPlayingBeforeFocusChange = player.isPlaying();

          if (this.wasPlayingBeforeFocusChange) {
            this.pause(this.focusedPlayerKey, null);
          }
      } else {
          if (this.wasPlayingBeforeFocusChange) {
            this.play(this.focusedPlayerKey, null);
            this.wasPlayingBeforeFocusChange = false;
          }
      }
    }
  }
}
 
Example 3
Source File: RNSoundModule.java    From react-native-sound with MIT License 6 votes vote down vote up
@ReactMethod
public void stop(final Double key, final Callback callback) {
  MediaPlayer player = this.playerPool.get(key);
  if (player != null && player.isPlaying()) {
    player.pause();
    player.seekTo(0);
  }

  // Release audio focus in Android system
  if (!this.mixWithOthers && key == this.focusedPlayerKey) {
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    audioManager.abandonAudioFocus(this);
  }

  callback.invoke();
}
 
Example 4
Source File: KcaUtils.java    From kcanotify 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 5
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 6
Source File: AuthenticationInstructionHelper.java    From ml-authentication with Apache License 2.0 5 votes vote down vote up
public static synchronized void playTabletPlacementOverlay(MediaPlayer mediaPlayerTabletPlacement, MediaPlayer mediaPlayerTabletPlacementOverlay, MediaPlayer mediaPlayerAnimalSound){
    // Check that the MediaPlayers are not null (this could happen, if the Activity has already ended, but a thread still tries to use the MediaPlayers)
    if ((mediaPlayerTabletPlacementOverlay != null) && (mediaPlayerAnimalSound != null)){
        if (mediaPlayerTabletPlacement != null){
            if ((!mediaPlayerTabletPlacement.isPlaying()) && (!mediaPlayerTabletPlacementOverlay.isPlaying()) && (!mediaPlayerAnimalSound.isPlaying())){
                mediaPlayerTabletPlacementOverlay.start();
            }
        } else {
            if ((!mediaPlayerTabletPlacementOverlay.isPlaying()) && (!mediaPlayerAnimalSound.isPlaying())){
                mediaPlayerTabletPlacementOverlay.start();
            }
        }
    }
}
 
Example 7
Source File: RNSoundModule.java    From react-native-sound with MIT License 5 votes vote down vote up
@ReactMethod
public void pause(final Double key, final Callback callback) {
  MediaPlayer player = this.playerPool.get(key);
  if (player != null && player.isPlaying()) {
    player.pause();
  }

  if (callback != null) {
    callback.invoke();
  }
}
 
Example 8
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 9
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 10
Source File: AlarmReceiver.java    From RhymeMusic with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent)
{
    Log.d(TAG, SUB + "音乐自动停止播放了");

    MusicApplication application = (MusicApplication) context.getApplicationContext();
    MediaPlayer mediaPlayer = application.getMediaPlayer();
    MusicService.MusicBinder musicBinder = application.getMusicBinder();

    if ( mediaPlayer != null && mediaPlayer.isPlaying() )
    {
        musicBinder.pausePlay();
    }
}
 
Example 11
Source File: WebVideoPresenter.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 12
Source File: KcUtils.java    From GotoBrowser with GNU General Public License v3.0 5 votes vote down vote up
public static boolean checkIsPlaying (MediaPlayer player) {
    if (player == null) return false;
    try {
        return player.isPlaying();
    } catch (IllegalStateException e) {
        return false;
    }
}
 
Example 13
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 14
Source File: SoundManager.java    From Camdroid with Apache License 2.0 5 votes vote down vote up
private void stop(final MediaPlayer mp) {
	if (mp == null)
		return;

	final Handler handler = new Handler();
	final float currentVolume = SoundManager.this.currentVolume();

	synchronized (mp) {
		Runnable mute = new Runnable() {
			float volume = currentVolume;

			@Override
			public void run() {
				boolean playing = false;
				try {
					playing = mp.isPlaying();
				} catch (IllegalStateException e) {
					return;
				}
				if (playing) {
					if (this.volume > 0.0f) {
						this.volume -= .25f;
						Log.d(TAG, "mp: " + mp.getAudioSessionId()
								+ " mute to: " + this.volume);
						mp.setVolume(this.volume, this.volume);
						handler.postDelayed(this, 250);
					} else {
						Log.d(TAG, "mp: " + mp.getAudioSessionId()
								+ " pause");
						mp.pause();
						mp.seekTo(0);
					}
				}
			}
		};

		handler.post(mute);
	}
}
 
Example 15
Source File: MyPlayer.java    From prayer-times-android with Apache License 2.0 5 votes vote down vote up
private MediaPlayer getMediaPlayer() {
    if (mediaPlayers == null) return null;
    for (MediaPlayer mp : mediaPlayers) {
        if (mp.isPlaying()) return mp;
    }
    return null;
}
 
Example 16
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 17
Source File: BGMFader.java    From SchoolQuest with GNU General Public License v3.0 5 votes vote down vote up
public static void start(final MediaPlayer mediaPlayer, int fadeDuration) {
    if (fadeDuration > 0) { iVolume = INT_VOLUME_MIN; }
    else { iVolume = INT_VOLUME_MAX; }

    updateVolume(mediaPlayer, 0);

    if (!mediaPlayer.isPlaying()) { mediaPlayer.start(); }

    if (fadeDuration > 0) {
        final Timer timer = new Timer(true);
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                updateVolume(mediaPlayer, 1);
                if (iVolume == INT_VOLUME_MAX) {
                    timer.cancel();
                    timer.purge();
                }
            }
        };

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

        timer.schedule(timerTask, delay, delay);
    }
}
 
Example 18
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 19
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 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;

    }

}