List of usage examples for android.media MediaPlayer MediaPlayer
public MediaPlayer()
From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java
/** * ???(Id?)./*w w w . j a va 2s . c o m*/ * * @param response ? * @param mediaId MediaID */ public void putMediaId(final Intent response, final String mediaId) { mCurrentMediaId = mediaId; // Video???? Uri mUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, Long.valueOf(mediaId)); String filePath = getPathFromUri(mUri); // null??Audio???? if (filePath == null) { mUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.valueOf(mediaId)); filePath = getPathFromUri(mUri); } String mMineType = getMIMEType(filePath); // ?? if ("audio/mpeg".equals(mMineType) || "audio/x-wav".equals(mMineType) || "application/ogg".equals(mMineType) || "audio/x-ms-wma".equals(mMineType) || "audio/mp3".equals(mMineType) || "audio/ogg".equals(mMineType) || "audio/mp4".equals(mMineType)) { mMediaPlayer = new MediaPlayer(); try { mSetMediaType = MEDIA_TYPE_MUSIC; myCurrentFilePath = filePath; myCurrentFileMIMEType = mMineType; mMediaStatus = MEDIA_PLAYER_SET; mMediaPlayer.setDataSource(filePath); mMediaPlayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(final MediaPlayer arg0) { mMediaStatus = MEDIA_PLAYER_STOP; sendOnStatusChangeEvent("stop"); } }); response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_OK); response.putExtra(DConnectMessage.EXTRA_VALUE, "regist:" + filePath); sendOnStatusChangeEvent("media"); sendBroadcast(response); } catch (IOException e) { response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.EXTRA_ERROR_CODE); response.putExtra(DConnectMessage.EXTRA_VALUE, "can't not regist:" + filePath); sendBroadcast(response); } } else if ("video/3gpp".equals(mMineType) || "video/mp4".equals(mMineType) || "video/m4v".equals(mMineType) || "video/3gpp2".equals(mMineType) || "video/mpeg".equals(mMineType)) { try { mSetMediaType = MEDIA_TYPE_VIDEO; myCurrentFilePath = filePath; myCurrentFileMIMEType = mMineType; response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_OK); response.putExtra(DConnectMessage.EXTRA_VALUE, "regist:" + filePath); sendOnStatusChangeEvent("media"); sendBroadcast(response); } catch (Exception e) { response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.EXTRA_ERROR_CODE); response.putExtra(DConnectMessage.EXTRA_VALUE, "can't not mount:" + filePath); sendBroadcast(response); } } else { response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.EXTRA_ERROR_CODE); response.putExtra(DConnectMessage.EXTRA_VALUE, "can't not open:" + filePath); sendBroadcast(response); } }
From source file:androidx.media.widget.VideoView2.java
private void openVideo(Uri uri, Map<String, String> headers) { resetPlayer();/*w w w . j a va 2 s .c o m*/ if (isRemotePlayback()) { // TODO (b/77158231) // mRoutePlayer.openVideo(dsd); return; } try { Log.d(TAG, "openVideo(): creating new MediaPlayer instance."); mMediaPlayer = new MediaPlayer(); mSurfaceView.setMediaPlayer(mMediaPlayer); mTextureView.setMediaPlayer(mMediaPlayer); mCurrentView.assignSurfaceToMediaPlayer(mMediaPlayer); final Context context = getContext(); // TODO: Add timely firing logic for more accurate sync between CC and video frame // mSubtitleController = new SubtitleController(context); // mSubtitleController.registerRenderer(new ClosedCaptionRenderer(context)); // mSubtitleController.setAnchor((SubtitleController.Anchor) mSubtitleView); mMediaPlayer.setOnPreparedListener(mPreparedListener); mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener); mMediaPlayer.setOnCompletionListener(mCompletionListener); mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener); mMediaPlayer.setOnErrorListener(mErrorListener); mMediaPlayer.setOnInfoListener(mInfoListener); mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener); mCurrentBufferPercentage = -1; mMediaPlayer.setDataSource(getContext(), uri, headers); mMediaPlayer.setAudioAttributes(mAudioAttributes); // mMediaPlayer.setOnSubtitleDataListener(mSubtitleListener); // we don't set the target state here either, but preserve the // target state that was there before. mCurrentState = STATE_PREPARING; mMediaPlayer.prepareAsync(); // Save file name as title since the file may not have a title Metadata. mTitle = uri.getPath(); String scheme = uri.getScheme(); if (scheme != null && scheme.equals("file")) { mTitle = uri.getLastPathSegment(); } mRetriever = new MediaMetadataRetriever(); mRetriever.setDataSource(getContext(), uri); if (DEBUG) { Log.d(TAG, "openVideo(). mCurrentState=" + mCurrentState + ", mTargetState=" + mTargetState); } } catch (IOException | IllegalArgumentException ex) { Log.w(TAG, "Unable to open content: " + uri, ex); mCurrentState = STATE_ERROR; mTargetState = STATE_ERROR; mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, MediaPlayer.MEDIA_ERROR_IO); } }
From source file:org.telegram.ui.ChatActivity.java
private void stopRecording() { try {//from w ww. ja v a 2s . com audioRecorder.stop(); audioRecorder.release(); audioRecorder = null; recordingAudio.date = ConnectionsManager.Instance.getCurrentTime(); recordingAudio.size = (int) recordingAudioFile.length(); recordingAudio.path = recordingAudioFile.getAbsolutePath(); int duration = 0; MediaPlayer player = new MediaPlayer(); try { player.setDataSource(recordingAudio.path); player.prepare(); duration = player.getDuration(); recordingAudio.duration = duration / 1000; } catch (Exception e) { FileLog.e("tmessages", e); } finally { try { player.release(); player = null; } catch (Exception e) { FileLog.e("tmessages", e); } } if (duration > 500) { MessagesController.Instance.sendMessage(recordingAudio, dialog_id); } else { recordingAudio = null; recordingAudioFile.delete(); recordingAudioFile = null; } } catch (Exception e) { FileLog.e("tmessages", e); recordingAudio = null; recordingAudioFile.delete(); recordingAudioFile = null; } }
From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java
private void setAudio(final GalleryItemViewTag tag, final File file) { runOnUiThread(new Runnable() { @Override/*from w w w . java2s .c om*/ public void run() { setOnClickView(tag, getString(R.string.gallery_tap_to_play), new View.OnClickListener() { @Override public void onClick(View v) { if (!settings.useInternalAudioPlayer()) { openExternal(); } else { recycleTag(tag, false); final TextView durationView = new TextView(GalleryActivity.this); durationView.setGravity(Gravity.CENTER); tag.layout.setVisibility(View.VISIBLE); tag.layout.addView(durationView); tag.audioPlayer = new MediaPlayer(); tag.audioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(final MediaPlayer mp) { mp.setLooping(true); durationView.setText( getSpannedText("00:00 / " + formatMediaPlayerTime(mp.getDuration()))); tag.timer = new Timer(); tag.timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { try { durationView.setText(getSpannedText( formatMediaPlayerTime(mp.getCurrentPosition()) + " / " + formatMediaPlayerTime(mp.getDuration()))); } catch (Exception e) { Logger.e(TAG, e); tag.timer.cancel(); } } }); } }, 1000, 1000); mp.start(); } }); tag.audioPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Logger.e(TAG, "(Audio) Error code: " + what); if (tag.timer != null) tag.timer.cancel(); showError(tag, getString(R.string.gallery_error_play)); return true; } }); try { tag.audioPlayer.setDataSource(file.getAbsolutePath()); tag.audioPlayer.prepareAsync(); } catch (Exception e) { Logger.e(TAG, "audio player error", e); if (tag.timer != null) tag.timer.cancel(); showError(tag, getString(R.string.gallery_error_play)); } } } }); } }); }
From source file:com.kjsaw.alcosys.ibacapp.IBAC.java
private void initBeepSound() { if (mediaPlayerBeep == null) { setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayerBeep = new MediaPlayer(); mediaPlayerBeep.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayerBeep.setOnCompletionListener(beepListener); AssetFileDescriptor fileBeep = getResources().openRawResourceFd(R.raw.beep); try {//from www .j a v a2s . co m mediaPlayerBeep.setDataSource(fileBeep.getFileDescriptor(), fileBeep.getStartOffset(), fileBeep.getLength()); fileBeep.close(); mediaPlayerBeep.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayerBeep.prepare(); } catch (IOException e) { mediaPlayerBeep = null; } } }
From source file:org.moire.ultrasonic.service.DownloadServiceImpl.java
private synchronized void setupNext(final DownloadFile downloadFile) { try {// w w w . ja v a2 s . c o m final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile() : downloadFile.getPartialFile(); if (nextMediaPlayer != null) { nextMediaPlayer.setOnCompletionListener(null); nextMediaPlayer.release(); nextMediaPlayer = null; } nextMediaPlayer = new MediaPlayer(); nextMediaPlayer.setWakeMode(DownloadServiceImpl.this, PowerManager.PARTIAL_WAKE_LOCK); try { nextMediaPlayer.setAudioSessionId(mediaPlayer.getAudioSessionId()); } catch (Throwable e) { nextMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } nextMediaPlayer.setDataSource(file.getPath()); setNextPlayerState(PREPARING); nextMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override @SuppressLint("NewApi") public void onPrepared(MediaPlayer mp) { try { setNextPlayerState(PREPARED); if (Util.getGaplessPlaybackPreference(DownloadServiceImpl.this) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && (playerState == PlayerState.STARTED || playerState == PlayerState.PAUSED)) { mediaPlayer.setNextMediaPlayer(nextMediaPlayer); nextSetup = true; } } catch (Exception x) { handleErrorNext(x); } } }); nextMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mediaPlayer, int what, int extra) { Log.w(TAG, String.format("Error on playing next (%d, %d): %s", what, extra, downloadFile)); return true; } }); nextMediaPlayer.prepareAsync(); } catch (Exception x) { handleErrorNext(x); } }
From source file:com.kjsaw.alcosys.ibacapp.IBAC.java
private void initCaptureSound() { if (mediaPlayerCapture == null) { setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayerCapture = new MediaPlayer(); mediaPlayerCapture.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayerCapture.setOnCompletionListener(captureListener); AssetFileDescriptor fileBeep = getResources().openRawResourceFd(R.raw.camera_flash); try {//from w ww. j av a 2 s.c o m mediaPlayerCapture.setDataSource(fileBeep.getFileDescriptor(), fileBeep.getStartOffset(), fileBeep.getLength()); fileBeep.close(); mediaPlayerCapture.setVolume(CAPTURE_VOLUME, CAPTURE_VOLUME); mediaPlayerCapture.prepare(); } catch (IOException e) { mediaPlayerCapture = null; } } }
From source file:com.quwu.xinwo.release.Release_Activity.java
/** * /*w ww . j a va2s . c om*/ * */ private void isPlayRecording() { MediaPlayer mPlayer = null; long duration = 0; mPlayer = new MediaPlayer(); MediaPlayer mp = MediaPlayer.create(Release_Activity.this, Uri.parse(path)); if (mp != null) { duration = mp.getDuration() / 1000; } try { mPlayer.setDataSource(path); mPlayer.prepare(); mPlayer.start(); } catch (IOException e) { } String str = duration % 60 + ""; playerBtn.setText(str + "s"); }
From source file:org.hermes.android.NotificationsController.java
private void playInChatSound() { if (!inChatSoundEnabled) { return;/*from w w w . j a va 2 s . c o m*/ } try { if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) { return; } } catch (Exception e) { FileLog.e("tmessages", e); } try { SharedPreferences preferences = ApplicationLoader.applicationContext .getSharedPreferences("Notifications", Context.MODE_PRIVATE); int notify_override = preferences.getInt("notify2_" + openned_dialog_id, 0); if (notify_override == 3) { int mute_until = preferences.getInt("notifyuntil_" + openned_dialog_id, 0); if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) { notify_override = 2; } } if (notify_override == 2) { return; } notificationsQueue.postRunnable(new Runnable() { @Override public void run() { if (lastSoundPlay > System.currentTimeMillis() - 500) { return; } try { if (mediaPlayerIn == null) { AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext .getResources().openRawResourceFd(R.raw.sound_in); if (assetFileDescriptor != null) { mediaPlayerIn = new MediaPlayer(); mediaPlayerIn.setAudioStreamType(AudioManager.STREAM_SYSTEM); mediaPlayerIn.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength()); mediaPlayerIn.setLooping(false); assetFileDescriptor.close(); mediaPlayerIn.prepare(); } } mediaPlayerIn.start(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); /*String choosenSoundPath = null; String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath(); choosenSoundPath = preferences.getString("sound_path_" + openned_dialog_id, null); boolean isChat = (int)(openned_dialog_id) < 0; if (isChat) { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath); } } else { if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) { choosenSoundPath = null; } else if (choosenSoundPath == null) { choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath); } } if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) { if (lastMediaPlayerUri == null || !choosenSoundPath.equals(lastMediaPlayerUri)) { lastMediaPlayerUri = choosenSoundPath; mediaPlayer.reset(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION); if (choosenSoundPath.equals(defaultPath)) { mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI); } else { mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Uri.parse(choosenSoundPath)); } mediaPlayer.prepare(); } mediaPlayer.start(); }*/ } catch (Exception e) { FileLog.e("tmessages", e); } }
From source file:org.hermes.android.NotificationsController.java
public void playOutChatSound() { if (!inChatSoundEnabled) { return;//from ww w .jav a2 s. c om } try { if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) { return; } } catch (Exception e) { FileLog.e("tmessages", e); } notificationsQueue.postRunnable(new Runnable() { @Override public void run() { try { if (mediaPlayerOut == null) { AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext .getResources().openRawResourceFd(R.raw.sound_out); if (assetFileDescriptor != null) { mediaPlayerOut = new MediaPlayer(); mediaPlayerOut.setAudioStreamType(AudioManager.STREAM_SYSTEM); mediaPlayerOut.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength()); mediaPlayerOut.setLooping(false); assetFileDescriptor.close(); mediaPlayerOut.prepare(); } } mediaPlayerOut.start(); } catch (Exception e) { FileLog.e("tmessages", e); } } }); }