Java Code Examples for android.media.MediaPlayer

The following are top voted examples for showing how to use android.media.MediaPlayer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: letv   File: RedPacketDialog.java   Source Code and License 8 votes vote down vote up
private void soundShake() {
    try {
        this.mPlayer = MediaPlayer.create(RedPacketSdkManager.getInstance().getApplicationContext(), R.raw.shake_sound);
        if (this.mPlayer != null) {
            this.mPlayer.start();
            this.mPlayer.setOnCompletionListener(new OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    RedPacketDialog.this.mPlayer.release();
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (this.mPlayer != null) {
            this.mPlayer.release();
        }
    }
}
 
Example 2
Project: ParsingPlayer   File: ParsingPlayerProxy.java   Source Code and License 8 votes vote down vote up
private String errToStr(int framework_err, int impl_err) {
    String msg = null;
    if (framework_err == MediaPlayer.MEDIA_ERROR_IO) {
        msg = "IO Error";
    } else if (framework_err == MediaPlayer.MEDIA_ERROR_MALFORMED) {
        msg = "Bitstream unsupported";
    } else if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
        msg = "Invalid progressive playback";
    } else if (framework_err == MediaPlayer.MEDIA_ERROR_TIMED_OUT) {
        msg = "Operation time out";
    } else if (framework_err == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
        msg = "MediaPlayer died";
    } else if (framework_err == MediaPlayer.MEDIA_ERROR_UNSUPPORTED) {
        msg = "File spec is not supported in the media framework";
    } else if (framework_err == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
        msg = "Unknown error";
    }
    return msg;
}
 
Example 3
Project: QRScanner   File: BeepManager.java   Source Code and License 7 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    try {
        AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
        } finally {
            file.close();
        }
        mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
        mediaPlayer.prepare();
        return mediaPlayer;
    } catch (IOException ioe) {
        Log.w(TAG, ioe);
        mediaPlayer.release();
        return null;
    }
}
 
Example 4
Project: react-native-videoplayer   File: ReactVideoView.java   Source Code and License 6 votes vote down vote up
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
    switch (what) {
        case MediaPlayer.MEDIA_INFO_BUFFERING_START:
            mEventEmitter.receiveEvent(getId(), Events.EVENT_STALLED.toString(), Arguments.createMap());
            break;
        case MediaPlayer.MEDIA_INFO_BUFFERING_END:
            mEventEmitter.receiveEvent(getId(), Events.EVENT_RESUME.toString(), Arguments.createMap());
            break;
        case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
            mEventEmitter.receiveEvent(getId(), Events.EVENT_READY_FOR_DISPLAY.toString(), Arguments.createMap());
            break;

        default:
    }
    return false;
}
 
Example 5
Project: youtube_background_android   File: DownloadedFragment.java   Source Code and License 6 votes vote down vote up
@Override
    public void onPrepared(MediaPlayer mp) {
        if(mHasVideo) {
            mediaPlayer.start();
            mediaPlayer.setVolume(0,0);
            setVideoSize();
            vidSurface.bringToFront();
            vidSurface.requestFocus();
            MediaController mController = new MediaController(context);
            mController.setMediaPlayer(this);
            mController.setAnchorView(vidSurface);

//        mController.show(0);
            vidSurface.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
                }
            });
        }
    }
 
Example 6
Project: lokey   File: IME.java   Source Code and License 6 votes vote down vote up
private void initializeMedia() {
    mediaEight[0] = MediaPlayer.create(getApplicationContext(), R.raw.eight_1);
    mediaEight[1] = MediaPlayer.create(getApplicationContext(), R.raw.eight_2);
    mediaEight[2] = MediaPlayer.create(getApplicationContext(), R.raw.eight_3);
    mediaEight[3] = MediaPlayer.create(getApplicationContext(), R.raw.eight_4);
    mediaEight[4] = MediaPlayer.create(getApplicationContext(), R.raw.eight_5);
    mediaEight[5] = MediaPlayer.create(getApplicationContext(), R.raw.eight_7);
    mediaEight[6] = MediaPlayer.create(getApplicationContext(), R.raw.eight_8);

    mediaEight[0].setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaEight[1].setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaEight[2].setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaEight[3].setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaEight[4].setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaEight[5].setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaEight[6].setAudioStreamType(AudioManager.STREAM_MUSIC);
}
 
Example 7
Project: Logistics-guard   File: MessageFragment.java   Source Code and License 6 votes vote down vote up
private void playRecord() throws IOException {

        File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "AAAAAAAAA");
        if (dir.exists()) {
            File[] files = dir.listFiles();
            if (files.length > 0) {
                mediaPlayer.setDataSource(files[0].getAbsolutePath());
                mediaPlayer.prepare();
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mediaPlayer.start();
                    }
                });
            }
        }
    }
 
Example 8
Project: AndroidTvDemo   File: AndroidMediaPlayer.java   Source Code and License 6 votes vote down vote up
public AndroidMediaPlayer() {
    synchronized (mInitLock) {
        mInternalMediaPlayer = new MediaPlayer();
    }
    mInternalMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mInternalListenerAdapter = new AndroidMediaPlayerListenerHolder(this);
    attachInternalListeners();
}
 
Example 9
Project: react-native-sound-player   File: RNSoundPlayerModule.java   Source Code and License 6 votes vote down vote up
@ReactMethod
public void playSoundFile(String name, String type) throws IOException {
  if (this.mediaPlayer == null) {
    int soundResID = getReactApplicationContext().getResources().getIdentifier(name, "raw", getReactApplicationContext().getPackageName());
    this.mediaPlayer = MediaPlayer.create(getCurrentActivity(), soundResID);
    this.mediaPlayer.setOnCompletionListener(
      new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer arg0) {
          WritableMap params = Arguments.createMap();
          params.putBoolean("success", true);
          sendEvent(getReactApplicationContext(), "FinishedPlaying", params);
        }
    });
  } else {
    Uri uri = Uri.parse("android.resource://" + getReactApplicationContext().getPackageName() + "/raw/" + name);
    this.mediaPlayer.reset();
    this.mediaPlayer.setDataSource(getCurrentActivity(), uri);
    this.mediaPlayer.prepare();
  }
  this.mediaPlayer.start();
}
 
Example 10
Project: SmartButler   File: BeepManager.java   Source Code and License 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    try {
        AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
        } finally {
            file.close();
        }
        mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
        mediaPlayer.prepare();
        return mediaPlayer;
    } catch (IOException ioe) {
        Log.w(TAG, ioe);
        mediaPlayer.release();
        return null;
    }
}
 
Example 11
Project: Android-Bubble-Game   File: GamePanel.java   Source Code and License 6 votes vote down vote up
public static void chimeSound() {
  ((Activity) MainMenu.getAppContext()).runOnUiThread(new Runnable() {
    public void run() {
      final MediaPlayer mp1 = MediaPlayer.create(MainMenu.getAppContext(), R.raw.chime);
      mp1.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
          mp1.release();
        }

      });
      mp1.start();
    }
  });
}
 
Example 12
Project: DroidStreamingDemo   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //initializing button
    btn = findViewById(R.id.play);

    //initializing mediaPlayer object
    mediaPlayer = new MediaPlayer();

    //setting streaming type
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    //setting clickListener on button
    btn.setOnClickListener(pausePlay);

}
 
Example 13
Project: TestChat   File: ImageDisplayActivity.java   Source Code and License 6 votes vote down vote up
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
                case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                        // 音频和视频数据不正确
                        break;
                case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                        if (!isFinishing())
                                mSurfaceVideoView.pause();
                        break;
                case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                        if (!isFinishing())
                                mSurfaceVideoView.start();
                        break;
                case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                        if (DeviceUtils.hasJellyBean()) {
                                mSurfaceVideoView.setBackground(null);
                        } else {
                                mSurfaceVideoView.setBackgroundDrawable(null);
                        }
                        break;
        }
        return false;
}
 
Example 14
Project: VideoWallPager   File: VideoLiveWallPaper.java   Source Code and License 6 votes vote down vote up
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
    super.onSurfaceCreated(holder);
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setSurface(holder.getSurface());
    try {
        AssetManager assets = getApplicationContext().getAssets();
        AssetFileDescriptor descriptor = assets.openFd("text1.mp4");
        mMediaPlayer.setDataSource(descriptor.getFileDescriptor(),descriptor.getStartOffset(),descriptor.getLength());
        mMediaPlayer.setLooping(true);
        mMediaPlayer.setVolume(1.0f,1.0f);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 15
Project: TripBuyer   File: LCIMAudioHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 播放语音文件
 *
 * @param path
 * @param finishCallback
 */
public synchronized void playAudio(String path, Runnable finishCallback) {
  if (onceStart) {
    mediaPlayer.reset();
  }
  tryRunFinishCallback();
  audioPath = path;
  LCIMAudioHelper.this.finishCallback = finishCallback;
  try {
    mediaPlayer.setDataSource(path);
    mediaPlayer.prepare();
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
      @Override
      public void onCompletion(MediaPlayer mp) {
        tryRunFinishCallback();
      }
    });
    mediaPlayer.start();
    onceStart = true;
  } catch (IOException e) {
  }
}
 
Example 16
Project: MyFire   File: BeepManager.java   Source Code and License 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
	MediaPlayer mediaPlayer = new MediaPlayer();
	mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
	mediaPlayer.setOnCompletionListener(this);
	mediaPlayer.setOnErrorListener(this);
	try {
		AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
		try {
			mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
		} finally {
			file.close();
		}
		mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
		mediaPlayer.prepare();
		return mediaPlayer;
	} catch (IOException ioe) {
		Log.w(TAG, ioe);
		mediaPlayer.release();
		return null;
	}
}
 
Example 17
Project: AI-Powered-Intelligent-Banking-Platform   File: AlexaAudioPlayer.java   Source Code and License 5 votes vote down vote up
@Override
public void onCompletion(MediaPlayer mp) {
    for(Callback callback: mCallbacks){
        callback.playerProgress(mItem, 1, 1);
        callback.itemComplete(mItem);
    }
}
 
Example 18
Project: BookReader-master   File: TypeTextView.java   Source Code and License 5 votes vote down vote up
private void playAudio(int audioResId) {
    try {
        stopAudio();
        mMediaPlayer = MediaPlayer.create(mContext, audioResId);
        mMediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 19
Project: react-native-videoplayer   File: FullscreenPlayer.java   Source Code and License 5 votes vote down vote up
@Override
    public void onCompletion(MediaPlayer mp) {
//        this.complete();
        if(this.tinyPlayer!=null){
            tinyPlayer.complete();
            tinyPlayer.exitFullscreen();
        }

//        super.onCompletion(mp);
    }
 
Example 20
Project: Android-AudioRecorder-App   File: PlayListFragment.java   Source Code and License 5 votes vote down vote up
@Override public void startMediaPlayer(int position, RecordingItem recordingItem)
    throws IOException {
  mMediaPlayer = new MediaPlayer();
  mMediaPlayer.setDataSource(recordingItem.getFilePath());
  mMediaPlayer.prepare();
  mMediaPlayer.setOnPreparedListener(MediaPlayer::start);
  mMediaPlayer.setOnCompletionListener(mp -> playListPresenter.mediaPlayerStopped());
  Log.i("Debug ", "Started");
}
 
Example 21
Project: LucaHome-AndroidApplication   File: CenterViewController.java   Source Code and License 5 votes vote down vote up
private void initializeMediaPlayer() {
    _radioPlayer = new MediaPlayer();

    try {
        _radioPlayer.setDataSource(_radioStream.GetUrl());
    } catch (Exception e) {
        Logger.getInstance().Error(TAG, e.getMessage());
        Toasty.error(_context, "An error appeared settings url for radio player!", Toast.LENGTH_LONG).show();
    }

    _radioPlayer.setOnBufferingUpdateListener((mediaPlayer, percent) -> Logger.getInstance().Information(TAG, String.format(Locale.getDefault(), "Buffered to %d%%", percent)));
    _radioPlayer.setOnPreparedListener(mediaPlayer -> _radioPlayer.start());
}
 
Example 22
Project: Hello-Music-droid   File: MusicService.java   Source Code and License 5 votes vote down vote up
@Override
public void onCompletion(final MediaPlayer mp) {
    if (mp == mCurrentMediaPlayer && mNextMediaPlayer != null) {
        mCurrentMediaPlayer.release();
        mCurrentMediaPlayer = mNextMediaPlayer;
        mNextMediaPath = null;
        mNextMediaPlayer = null;
        mHandler.sendEmptyMessage(TRACK_WENT_TO_NEXT);
    } else {
        mService.get().mWakeLock.acquire(30000);
        mHandler.sendEmptyMessage(TRACK_ENDED);
        mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
    }
}
 
Example 23
Project: alpha-movie   File: AlphaMovieView.java   Source Code and License 5 votes vote down vote up
private void prepareAsync(final MediaPlayer.OnPreparedListener onPreparedListener) {
    if (mediaPlayer != null && state == PlayerState.NOT_PREPARED
            || state == PlayerState.STOPPED) {
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                state = PlayerState.PREPARED;
                onPreparedListener.onPrepared(mp);
            }
        });
        mediaPlayer.prepareAsync();
    }
}
 
Example 24
Project: GravityBox   File: QuickRecordTile.java   Source Code and License 5 votes vote down vote up
private void startPlaying() {
    mPlayer = new MediaPlayer();
    try {
        mPlayer.setDataSource(mAudioFileName);
        mPlayer.prepare();
        mPlayer.start();
        mRecordingState = STATE_PLAYING;
        refreshState();
        mPlayer.setOnCompletionListener(stoppedPlaying);
    } catch (IOException e) {
        log(getKey() + ": startPlaying failed: " + e.getMessage());
    }
}
 
Example 25
Project: PicShow-zhaipin   File: JCVideoPlayer.java   Source Code and License 5 votes vote down vote up
public void onInfo(int what, int extra) {
    Log.d(TAG, "onInfo what - " + what + " extra - " + extra);
    if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
        BACKUP_PLAYING_BUFFERING_STATE = currentState;
        setUiWitStateAndScreen(CURRENT_STATE_PLAYING_BUFFERING_START);//没这个case
        Log.d(TAG, "MEDIA_INFO_BUFFERING_START");
    } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
        if (BACKUP_PLAYING_BUFFERING_STATE != -1) {
            setUiWitStateAndScreen(BACKUP_PLAYING_BUFFERING_STATE);
            BACKUP_PLAYING_BUFFERING_STATE = -1;
        }
        Log.d(TAG, "MEDIA_INFO_BUFFERING_END");
    }
}
 
Example 26
Project: HeadlineNews   File: JCMediaManager.java   Source Code and License 5 votes vote down vote up
@Override
public void onCompletion(MediaPlayer mp) {
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            if (JCVideoPlayerManager.getCurrentJcvd() != null) {
                JCVideoPlayerManager.getCurrentJcvd().onAutoCompletion();
            }
        }
    });
}
 
Example 27
Project: Quran   File: AudioService.java   Source Code and License 5 votes vote down vote up
@Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
  Timber.d("seek complete! %d vs %d",
      mediaPlayer.getCurrentPosition(), mPlayer.getCurrentPosition());
  mPlayer.start();
  mHandler.sendEmptyMessageDelayed(MSG_UPDATE_AUDIO_POS, 200);
}
 
Example 28
Project: YZxing   File: BeepManager.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
    if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
        // we are finished, so put up an appropriate error toast if required and finish
        activity.finish();
    } else {
        // possibly media player error, so release and recreate
        close();
        updatePrefs();
    }
    return true;
}
 
Example 29
Project: CCDownload   File: ADMediaPlayActivity.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
	Message msg = new Message();
	msg.what = what;
	if (alertHandler != null) {
		alertHandler.sendMessage(msg);
	}
	return false;
}
 
Example 30
Project: letv   File: VideoViewH264m3u8Hw_4D.java   Source Code and License 5 votes vote down vote up
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
    VideoViewH264m3u8Hw_4D.this.mVideoWidth = mp.getVideoWidth();
    VideoViewH264m3u8Hw_4D.this.mVideoHeight = mp.getVideoHeight();
    if (!(VideoViewH264m3u8Hw_4D.this.mVideoWidth == 0 || VideoViewH264m3u8Hw_4D.this.mVideoHeight == 0)) {
        VideoViewH264m3u8Hw_4D.this.getHolder().setFixedSize(VideoViewH264m3u8Hw_4D.this.mVideoWidth, VideoViewH264m3u8Hw_4D.this.mVideoHeight);
    }
    if (VideoViewH264m3u8Hw_4D.this.mOnVideoSizeChangedListener != null) {
        VideoViewH264m3u8Hw_4D.this.mOnVideoSizeChangedListener.onVideoSizeChanged(mp, VideoViewH264m3u8Hw_4D.this.mVideoWidth, VideoViewH264m3u8Hw_4D.this.mVideoHeight);
    }
}
 
Example 31
Project: AssistantBySDK   File: VoiceInputComponent.java   Source Code and License 5 votes vote down vote up
/**
 * 构造函数
 */
public SpeechPlayer() {
    mPlayer = new MediaPlayer();
    timer = new Timer(true);
    mAssetManager = context.getAssets();
    mPlayer.setOnPreparedListener(this);
    mPlayer.setOnCompletionListener(this);
}
 
Example 32
Project: Underlined   File: SoundManager.java   Source Code and License 5 votes vote down vote up
public static void turnSoundOn() {
    isSoundOn = true;
    if(isplayingAudio){
        mediaPlayer = MediaPlayer.create(context, lastSound);
        mediaPlayer.start();
    }
}
 
Example 33
Project: 2017.2-codigo   File: MusicPlayerWithBindingService.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    // configurar media player
    mPlayer = MediaPlayer.create(this, R.raw.moonlightsonata);

    if (null != mPlayer) {
        //fica em loop
        mPlayer.setLooping(true);
    }


    // cria notificacao na area de notificacoes para usuario voltar p/ Activity
    final Intent notificationIntent = new Intent(getApplicationContext(), MusicPlayerWithBindingActivity.class);
    final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    final Notification notification = new Notification.Builder(
            getApplicationContext())
            .setSmallIcon(android.R.drawable.ic_media_play)
            .setOngoing(true).setContentTitle("Music Service rodando")
            .setContentText("Clique para acessar o player!")
            .setContentIntent(pendingIntent).build();

    // inicia em estado foreground, para ter prioridade na memoria
    // evita que seja facilmente eliminado pelo sistema
    startForeground(NOTIFICATION_ID, notification);
}
 
Example 34
Project: Things-Audio-Renderer   File: PlayerService.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);


    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constants.BA_NEW_TRACKLIST);
    intentFilter.addAction(Constants.BA_SKIP_NEXT);
    intentFilter.addAction(Constants.BA_SKIP_PREV);
    intentFilter.addAction(Constants.BA_PAUSE);
    intentFilter.addAction(Constants.BA_PLAY);
    registerReceiver(controlReceiver, intentFilter);

    progressDisposable = Observable.interval(1, TimeUnit.SECONDS).map(aLong -> mediaPlayer.getCurrentPosition() / 1000)
            .distinctUntilChanged()
            .subscribe(integer -> {
                PlayPosition playPosition = new PlayPosition();
                playPosition.setPosition(integer);
                Intent posInt = new Intent();
                posInt.putExtra(Constants.BK_PLAYBACKEVENT, playPosition);
                posInt.setAction(Constants.BA_PLAYBACKEVENT);

                sendBroadcast(posInt);
                Log.d("Player", "pos" + integer);
            });
}
 
Example 35
Project: android-PictureInPicture   File: MovieView.java   Source Code and License 5 votes vote down vote up
void openVideo(Surface surface) {
    if (mVideoResourceId == 0) {
        return;
    }
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setSurface(surface);
    startVideo();
}
 
Example 36
Project: QrCode   File: BeepManager.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
  if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
    // we are finished, so put up an appropriate error toast if required and finish
    activity.finish();
  } else {
    // possibly media player error, so release and recreate
    close();
    updatePrefs();
  }
  return true;
}
 
Example 37
Project: Discover   File: JZMediaSystem.java   Source Code and License 5 votes vote down vote up
@Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
    JZMediaManager.instance().mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            if (JZVideoPlayerManager.getCurrentJzvd() != null) {
                JZVideoPlayerManager.getCurrentJzvd().onSeekComplete();
            }
        }
    });
}
 
Example 38
Project: Quran   File: AudioService.java   Source Code and License 5 votes vote down vote up
/** Called when media player is done preparing. */
@Override
public void onPrepared(MediaPlayer player) {
  Timber.d("okay, prepared!");

  // The media player is done preparing. That means we can start playing!
  mState = State.Playing;
  if (mShouldStop) {
    processStopRequest();
    mShouldStop = false;
    return;
  }

  // if gapless and sura changed, get the new data
  if (mAudioRequest.isGapless()) {
    if (mGaplessSura != mAudioRequest.getCurrentSura()) {
      if (mTimingTask != null) {
        mTimingTask.cancel(true);
      }

      String dbPath = mAudioRequest.getGaplessDatabaseFilePath();
      mTimingTask = new ReadGaplessDataTask(dbPath);
      mTimingTask.execute(mAudioRequest.getCurrentSura());
    }
  }

  if (mPlayerOverride || !mAudioRequest.isGapless()) {
    notifyAyahChanged();
  }

  updateNotification();
  configAndStartMediaPlayer();
}
 
Example 39
Project: Espresso   File: BeepManager.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
	if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
		// we are finished, so put up an appropriate error toast if required
		// and finish
		activity.finish();
	} else {
		// possibly media player error, so release and recreate
		mp.release();
		mediaPlayer = null;
		updatePrefs();
	}
	return true;
}
 
Example 40
Project: android-ponewheel   File: AlertsView.java   Source Code and License 5 votes vote down vote up
@Override
public void recaptureMedia(Activity activity) {
    if (mediaPlayer == null) {
        mediaPlayer = MediaPlayer.create(activity, R.raw.siren);
    }
}
 
Example 41
Project: ThunderMusic   File: MediaPlaybackService.java   Source Code and License 5 votes vote down vote up
public void setDataSource(String path) {
    try {
        mOnlineDuration = 0;
        mCurrentMediaPlayer.reset();
        if (path.startsWith("content://")) {
            mCurrentMediaPlayer.setDataSource(
                    MediaPlaybackService.this, Uri.parse(path));
        } else {
            mCurrentMediaPlayer.setDataSource(path);
        }
        mCurrentMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        mCurrentMediaPlayer.prepareAsync();
        mCurrentMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mOnlineDuration = mCurrentMediaPlayer.getDuration();
                mp.setOnCompletionListener(listener);
                mp.setOnErrorListener(errorListener);
                setOnInfoListener();

                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
                mIsInitialized = true;
                notifyChange(META_CHANGED);
                notifyChange(END_BUFFERING);
            }
        });
    } catch (IOException ex) {
        mIsInitialized = false;
        return;
    }
}
 
Example 42
Project: getword   File: MainActivity.java   Source Code and License 5 votes vote down vote up
/**
 * 使用完MediaPlayer需要回收资源。MediaPlayer是很消耗系统资源的,所以在使用完MediaPlayer,不要等待系统自动回收,最好是主动回收资源。
 */
private void stopMedia(MediaPlayer mediaPlayer) {
    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
    }

}
 
Example 43
Project: ZXingAndroidExt   File: BeepManager.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
    if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
        // we are finished, so put up an appropriate error toast if required and finish
        activity.finish();
    } else {
        // possibly media player error, so release and recreate
        close();
        updatePrefs();
    }
    return true;
}
 
Example 44
Project: aos-MediaLib   File: MediaPlayerProxy.java   Source Code and License 5 votes vote down vote up
@Override
public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
    if (method.getName().equals("onTimedText") && args.length == 2) {
        String text = args[1] != null ? text = (String) sTimedTextGetText.invoke(args[1]) : null;
        mOnTimedTextListener.onTimedText((MediaPlayer) args[0], text);
    }
    return null;
}
 
Example 45
Project: Hitalk   File: TextureVideoView.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onInfo(final MediaPlayer mp, final int what, final int extra) {
    if (mMediaPlayerCallback != null) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if(mMediaPlayerCallback != null) {
                    mMediaPlayerCallback.onInfo(mp, what, extra);
                }
            }
        });
    }
    return true;
}
 
Example 46
Project: CommonsLab   File: MediaPlayerService.java   Source Code and License 5 votes vote down vote up
@Override
public void onCompletion(MediaPlayer mp) {
    //Invoked when playback of a media source has completed.
    stopMedia();

    removeNotification();
    //stop the service
    stopSelf();
}
 
Example 47
Project: boohee_v5.6   File: PlayerManager.java   Source Code and License 5 votes vote down vote up
@NonNull
public MediaPlayer getMediaPlayer(Uri uri) {
    if (hasPrevPlayer(uri)) {
        return this.mMediaPlayer;
    }
    releaseMediaPlayer();
    this.mMediaPlayer = createPlayer();
    this.mUri = uri;
    return this.mMediaPlayer;
}
 
Example 48
Project: AssistantBySDK   File: SpeechPlayer.java   Source Code and License 5 votes vote down vote up
@Override
  public void onCompletion(MediaPlayer mp) {
      Log.d(TAG, "onCompletion");
      //Log.e(TAG, "onCompletion::::"+(System.currentTimeMillis()-b));
      /*if(mPlayListener!=null&&Setting.MediaPlayerFast&&!LingjuRecognizer.getInstance().isLocalEngine()){
          mPlayListener.onPlayComplete();
}*/
      if (mPlayListener != null)
          mPlayListener.onPlayComplete();
  }
 
Example 49
Project: Customerly-Android-SDK   File: PW_AlertMessage.java   Source Code and License 5 votes vote down vote up
@UiThread
static void show(@NonNull Activity activity, @NonNull IE_Message message) throws WindowManager.BadTokenException {
    PW_AlertMessage alert = PW_AlertMessage._CurrentVisible;
    if (alert != null) {
        if(alert._MessageID == message.conversation_message_id) { //Already displaying that message
            alert.bindMessage(message);
            alert.abortFadeOut();
            alert.getContentView().postDelayed(alert._FadeOutAfterTOT, AUTO_FADE_OUT_DELAY);
            return;
        }
        if(activity == alert.getActivity()) {
            alert.fadeOut();
        } else {
            alert.dismissAllowingStateLoss();
        }
    }
    alert = new PW_AlertMessage(activity);
    alert.bindMessage(message);
    int top_offset_fix = 0;
    View decorView = activity.getWindow().getDecorView();
    if (decorView instanceof ViewGroup) {
        ViewGroup decorViewGroup = (ViewGroup) decorView;
        if (decorViewGroup.getChildCount() == 1) {
            top_offset_fix = decorViewGroup.getChildAt(0).getPaddingTop();
        }
    }
    alert.showAtLocation(activity.getWindow().getDecorView(), Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, top_offset_fix);
    PW_AlertMessage._CurrentVisible = alert;
    alert.getContentView().postDelayed(alert._FadeOutAfterTOT, AUTO_FADE_OUT_DELAY);
    MediaPlayer mp = MediaPlayer.create(activity, R.raw.notif_2);
    mp.setOnCompletionListener(mp1 -> {
        mp1.reset();
        mp1.release();
    });
    mp.start();
}
 
Example 50
Project: LocationAware   File: LocationAwareService.java   Source Code and License 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 51
Project: TherapyGuide   File: ListenService.java   Source Code and License 5 votes vote down vote up
@Override
public void play() {
    if (null == mMediaPlayer) {
        mMediaPlayer =
                MediaPlayer.create(getApplicationContext(), mTrack);
        mMediaPlayer.setLooping(mLooping);
    }
    startForeground(PLAYER_NOTIFICATION_ID, mPlayerNotification);
    mMediaPlayer.start();
    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer player) {
            stopForeground(true);
            if(null != mMediaPlayer) {
                mMediaPlayer.release();
            }
            mMediaPlayer = null;
            // Broadcast a notification so the app knows playback has completed
            Intent intent = new Intent();
            intent.setAction(FINISHED_PLAYBACK_NOTIFICATION);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

            stopForeground(true);
        }

    });
}
 
Example 52
Project: Phoenix-for-VK   File: DefaultVoicePlayer.java   Source Code and License 5 votes vote down vote up
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    if(Objects.nonNull(mErrorListener) && mPlayer == mp){
        mErrorListener.onPlayError(new Exception("Unable to play message, what: " + what + ", extra: " + extra));
    }
    return false;
}
 
Example 53
Project: MKVideoPlayer   File: AndroidMediaPlayer.java   Source Code and License 5 votes vote down vote up
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
    AndroidMediaPlayer self = mWeakMediaPlayer.get();
    if (self == null)
        return;

    notifyOnBufferingUpdate(percent);
}
 
Example 54
Project: start-guide   File: MediaPlayerHelper.java   Source Code and License 5 votes vote down vote up
public static void play(Context context, int resId, final MediaPlayerListener listener) {
    Log.i(MediaPlayerHelper.class.getName(), "play");

    final MediaPlayer mediaPlayer = MediaPlayer.create(context, resId);
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mediaPlayer.release();
            if (listener != null) {
                listener.onCompletion();
            }
        }
    });
    mediaPlayer.start();
}
 
Example 55
Project: RetroMusicPlayer   File: MultiPlayer.java   Source Code and License 5 votes vote down vote up
/**
 * @param player The {@link MediaPlayer} to use
 * @param path   The path of the file, or the http/rtsp URL of the stream
 *               you want to play
 * @return True if the <code>player</code> has been prepared and is
 * ready to play, false otherwise
 */
private boolean setDataSourceImpl(@NonNull final MediaPlayer player, @NonNull final String path) {
    if (context == null) {
        return false;
    }
    try {
        player.reset();
        player.setOnPreparedListener(null);
        if (path.startsWith("content://")) {
            player.setDataSource(context, Uri.parse(path));
        } else {
            player.setDataSource(path);
        }
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.prepare();
    } catch (Exception e) {
        return false;
    }
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
    intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
    intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName());
    intent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC);
    context.sendBroadcast(intent);
    return true;
}
 
Example 56
Project: AndroidTvDemo   File: AndroidTrackInfo.java   Source Code and License 5 votes vote down vote up
private static AndroidTrackInfo[] fromTrackInfo(MediaPlayer.TrackInfo[] trackInfos) {
    if (trackInfos == null)
        return null;

    AndroidTrackInfo androidTrackInfo[] = new AndroidTrackInfo[trackInfos.length];
    for (int i = 0; i < trackInfos.length; ++i) {
        androidTrackInfo[i] = new AndroidTrackInfo(trackInfos[i]);
    }

    return androidTrackInfo;
}
 
Example 57
Project: Phoenix-for-VK   File: DefaultVoicePlayer.java   Source Code and License 5 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mp) {
    if (mp != mPlayer) {
        return;
    }
    changeStatusTo(STATUS_PREPARED);

    if (mSupposedToPlay) {
        mPlayer.start();
    }
}
 
Example 58
Project: CodeScaner   File: BeepManager.java   Source Code and License 5 votes vote down vote up
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
  if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
    // we are finished, so put up an appropriate error toast if required and finish
    activity.finish();
  } else {
    // possibly media player error, so release and recreate
    close();
    updatePrefs();
  }
  return true;
}
 
Example 59
Project: UiLib   File: TestVideoActivity1.java   Source Code and License 4 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mp) {
    Log.e("lmsg","onprepare:"+System.currentTimeMillis());
    mp.start();

}
 
Example 60
Project: WeiXinRecordedDemo   File: MyVideoView.java   Source Code and License 4 votes vote down vote up
@Override
public void onSeekComplete(MediaPlayer mp) {
	if (mOnSeekCompleteListener != null)
		mOnSeekCompleteListener.onSeekComplete(mp);
}