List of usage examples for android.media MediaPlayer MediaPlayer
public MediaPlayer()
From source file:com.android.dialer.voicemail.VoicemailPlaybackPresenter.java
/** * Prepares the voicemail content for playback. * <p>/* w w w . j a v a 2 s .c o m*/ * This method will be called once we know that our voicemail has content (according to the * content provider). this method asynchronously tries to prepare the data source through the * media player. If preparation is successful, the media player will {@link #onPrepared()}, * and it will call {@link #onError()} otherwise. */ protected void prepareContent() { if (mView == null) { return; } Log.d(TAG, "prepareContent"); // Release the previous media player, otherwise there may be failures. if (mMediaPlayer != null) { mMediaPlayer.release(); mMediaPlayer = null; } mView.disableUiElements(); mIsPrepared = false; try { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnErrorListener(this); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.reset(); mMediaPlayer.setDataSource(mContext, mVoicemailUri); mMediaPlayer.setAudioStreamType(VoicemailAudioManager.PLAYBACK_STREAM); mMediaPlayer.prepareAsync(); } catch (IOException e) { handleError(e); } }
From source file:com.aujur.ebookreader.activity.ReadingFragment.java
private void playBeep(boolean error) { if (!isAdded()) { return;//from ww w . j ava 2 s .c o m } try { MediaPlayer beepPlayer = new MediaPlayer(); String file = "beep.mp3"; if (error) { file = "error.mp3"; } AssetFileDescriptor descriptor = context.getAssets().openFd(file); beepPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); descriptor.close(); beepPlayer.prepare(); beepPlayer.start(); } catch (Exception io) { // We'll manage without the beep :) } }
From source file:com.tsp.clipsy.audio.RingdroidEditActivity.java
private void loadFromFile() { mFile = new File(mFilename); mExtension = getExtensionFromFilename(mFilename); SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename); mTitle = metadataReader.mTitle;/*from w w w. j av a 2 s . c o m*/ mArtist = metadataReader.mArtist; mAlbum = metadataReader.mAlbum; mYear = metadataReader.mYear; mGenre = metadataReader.mGenre; String titleLabel = mTitle; if (mArtist != null && mArtist.length() > 0) { titleLabel += " - " + mArtist; } setTitle(titleLabel); mLoadingStartTime = System.currentTimeMillis(); mLoadingLastUpdateTime = System.currentTimeMillis(); mLoadingKeepGoing = true; mProgressDialog = new ProgressDialog(RingdroidEditActivity.this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle(R.string.progress_dialog_loading); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mLoadingKeepGoing = false; } }); mProgressDialog.show(); final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() { public boolean reportProgress(double fractionComplete) { long now = System.currentTimeMillis(); if (now - mLoadingLastUpdateTime > 100) { mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete)); mLoadingLastUpdateTime = now; } return mLoadingKeepGoing; } }; // Create the MediaPlayer in a background thread mCanSeekAccurately = false; new Thread() { public void run() { mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE)); System.out.println("Seek test done, creating media player."); try { MediaPlayer player = new MediaPlayer(); player.setDataSource(mFile.getAbsolutePath()); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.prepare(); mPlayer = player; } catch (final java.io.IOException e) { Runnable runnable = new Runnable() { public void run() { handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); } ; } }.start(); // Load the sound file in a background thread new Thread() { public void run() { try { mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener); if (mSoundFile == null) { mProgressDialog.dismiss(); String name = mFile.getName().toLowerCase(); String[] components = name.split("\\."); String err; if (components.length < 2) { err = getResources().getString(R.string.no_extension_error); } else { err = getResources().getString(R.string.bad_extension_error) + " " + components[components.length - 1]; } final String finalErr = err; Runnable runnable = new Runnable() { public void run() { handleFatalError("UnsupportedExtension", finalErr, new Exception()); } }; mHandler.post(runnable); return; } } catch (final Exception e) { mProgressDialog.dismiss(); e.printStackTrace(); mInfo.setText(e.toString()); Runnable runnable = new Runnable() { public void run() { handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); return; } mProgressDialog.dismiss(); if (mLoadingKeepGoing) { Runnable runnable = new Runnable() { public void run() { finishOpeningSoundFile(); } }; mHandler.post(runnable); } else { RingdroidEditActivity.this.finish(); } } }.start(); }
From source file:mobi.omegacentauri.ptimer.PTimerEditActivity.java
private void loadFromFile() { mFile = new File(mFilename); mExtension = getExtensionFromFilename(mFilename); SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename); mTitle = metadataReader.mTitle;//from w ww . j a va 2 s. c o m mArtist = metadataReader.mArtist; mAlbum = metadataReader.mAlbum; mYear = metadataReader.mYear; mGenre = metadataReader.mGenre; String titleLabel = mTitle; if (mArtist != null && mArtist.length() > 0) { titleLabel += " - " + mArtist; } setTitle(titleLabel); mLoadingStartTime = System.currentTimeMillis(); mLoadingLastUpdateTime = System.currentTimeMillis(); mLoadingKeepGoing = true; mProgressDialog = new ProgressDialog(PTimerEditActivity.this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle(R.string.progress_dialog_loading); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mLoadingKeepGoing = false; } }); mProgressDialog.show(); final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() { public boolean reportProgress(double fractionComplete) { long now = System.currentTimeMillis(); if (now - mLoadingLastUpdateTime > 100) { mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete)); mLoadingLastUpdateTime = now; } return mLoadingKeepGoing; } }; // Create the MediaPlayer in a background thread mCanSeekAccurately = false; new Thread() { public void run() { mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE)); System.out.println("Seek test done, creating media player."); try { MediaPlayer player = new MediaPlayer(); player.setDataSource(mFile.getAbsolutePath()); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.prepare(); mPlayer = player; } catch (final java.io.IOException e) { Runnable runnable = new Runnable() { public void run() { handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); } ; } }.start(); // Load the sound file in a background thread new Thread() { public void run() { try { mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener); if (mSoundFile == null) { mProgressDialog.dismiss(); String name = mFile.getName().toLowerCase(); String[] components = name.split("\\."); String err; if (components.length < 2) { err = getResources().getString(R.string.no_extension_error); } else { err = getResources().getString(R.string.bad_extension_error) + " " + components[components.length - 1]; } final String finalErr = err; Runnable runnable = new Runnable() { public void run() { handleFatalError("UnsupportedExtension", finalErr, new Exception()); } }; mHandler.post(runnable); return; } } catch (final Exception e) { mProgressDialog.dismiss(); e.printStackTrace(); mInfo.setText(e.toString()); Runnable runnable = new Runnable() { public void run() { handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); return; } mProgressDialog.dismiss(); if (mLoadingKeepGoing) { Runnable runnable = new Runnable() { public void run() { finishOpeningSoundFile(); } }; mHandler.post(runnable); } else { PTimerEditActivity.this.finish(); } } }.start(); }
From source file:com.cw.litenote.operation.audio.AudioPlayer_page.java
/** * Start new audio/*w w w. ja v a2 s . c o m*/ */ private void startNewAudio() { System.out.println( "AudioPlayer_page / _startNewAudio / Audio_manager.mAudioPos = " + Audio_manager.mAudioPos); // remove call backs to make sure next toast will appear soon if (mAudioHandler != null) mAudioHandler.removeCallbacks(page_runnable); mAudioHandler = null; mAudioHandler = new Handler(); Audio_manager.isRunnableOn_page = true; Audio_manager.isRunnableOn_note = false; BackgroundAudioService.mMediaPlayer = null; // verify audio URL Async_audioUrlVerify.mIsOkUrl = false; if ((Audio_manager.getAudioPlayMode() == Audio_manager.PAGE_PLAY_MODE) && (Audio_manager.getCheckedAudio(Audio_manager.mAudioPos) == 0)) { mAudioHandler.postDelayed(page_runnable, Util.oneSecond / 4); } else { mAudioUrlVerifyTask = new Async_audioUrlVerify(act, mAudioManager.getAudioStringAt(Audio_manager.mAudioPos)); mAudioUrlVerifyTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "Searching media ..."); while (!Async_audioUrlVerify.mIsOkUrl) { //wait for Url verification try { Thread.sleep(Util.oneSecond / 20); } catch (InterruptedException e) { e.printStackTrace(); } } // prepare audio if (Async_audioUrlVerify.mIsOkUrl) { showAudioPanel(act, true); // launch handler if ((Audio_manager.getPlayerState() != Audio_manager.PLAYER_AT_STOP) && (Audio_manager.getAudioPlayMode() == Audio_manager.PAGE_PLAY_MODE)) { mAudioHandler.postDelayed(page_runnable, Util.oneSecond / 4); } // during audio Preparing Async_audioPrepare mAsyncTaskAudioPrepare = new Async_audioPrepare(act); mAsyncTaskAudioPrepare.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "Preparing to play ..."); if (Build.VERSION.SDK_INT >= 21) { MediaControllerCompat.getMediaController(MainAct.mAct).getTransportControls() .playFromUri(Uri.parse(audioUrl_page), null); MediaControllerCompat.getMediaController(MainAct.mAct).getTransportControls().play(); } else { BackgroundAudioService.mMediaPlayer = new MediaPlayer(); BackgroundAudioService.mMediaPlayer.reset(); try { BackgroundAudioService.mMediaPlayer.setDataSource(act, Uri.parse(audioUrl_page)); // prepare the MediaPlayer to play, this will delay system response BackgroundAudioService.mMediaPlayer.prepare(); setAudioListeners(); } catch (Exception e) { Toast.makeText(act, R.string.audio_message_could_not_open_file, Toast.LENGTH_SHORT).show(); Audio_manager.stopAudioPlayer(); } } } } }
From source file:com.commontime.cordova.audio.AudioPlayer.java
/** * attempts to initialize the media player for playback * @param file the file to play//from w w w. java 2s .c o m * @return false if player not ready, reports if in wrong mode or state */ private boolean readyPlayer(String file) { if (playMode()) { switch (this.state) { case MEDIA_NONE: if (this.player == null) { this.player = new MediaPlayer(); } try { this.loadAudioFile(file); } catch (Exception e) { sendErrorStatus(MEDIA_ERR_ABORTED); } return false; case MEDIA_LOADING: //cordova js is not aware of MEDIA_LOADING, so we send MEDIA_STARTING instead Log.d(LOG_TAG, "AudioPlayer Loading: startPlaying() called during media preparation: " + STATE.MEDIA_STARTING.ordinal()); this.prepareOnly = false; return false; case MEDIA_STARTING: case MEDIA_RUNNING: case MEDIA_PAUSED: return true; case MEDIA_STOPPED: //if we are readying the same file if (this.audioFile.compareTo(file) == 0) { //reset the audio file player.seekTo(0); player.pause(); return true; } else { //reset the player this.player.reset(); try { this.loadAudioFile(file); } catch (Exception e) { sendErrorStatus(MEDIA_ERR_ABORTED); } //if we had to prepare the file, we won't be in the correct state for playback return false; } default: Log.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: " + this.state); sendErrorStatus(MEDIA_ERR_ABORTED); } } return false; }
From source file:net.nightwhistler.pageturner.fragment.ReadingFragment.java
private void streamPartToDisk(String fileName, String part, int offset, int totalLength, boolean endOfPage) throws TTSFailedException { LOG.debug("Request to stream text to file " + fileName + " with text " + part); if (part.trim().length() > 0 || endOfPage) { HashMap<String, String> params = new HashMap<>(); params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, fileName); TTSPlaybackItem item = new TTSPlaybackItem(part, new MediaPlayer(), totalLength, offset, endOfPage, fileName);//from w w w. j a v a 2s. c o m ttsItemPrep.put(fileName, item); int result; String errorMessage = ""; try { result = textToSpeech.synthesizeToFile(part, params, fileName); } catch (Exception e) { LOG.error("Failed to start TTS", e); result = TextToSpeech.ERROR; errorMessage = e.getMessage(); } if (result != TextToSpeech.SUCCESS) { String message = "Can't write to file \n" + fileName + " because of error\n" + errorMessage; LOG.error(message); showTTSFailed(message); throw new TTSFailedException(); } } else { LOG.debug("Skipping part, since it's empty."); } }
From source file:com.SpeechEd.SpeechEdEditActivity.java
private void loadFromFile() { mFile = new File(mFilename); mExtension = getExtensionFromFilename(mFilename); SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename); mTitle = metadataReader.mTitle;//from w ww . ja v a2 s .com mArtist = metadataReader.mArtist; mAlbum = metadataReader.mAlbum; mYear = metadataReader.mYear; mGenre = metadataReader.mGenre; String titleLabel = mTitle; if (mArtist != null && mArtist.length() > 0) { titleLabel += " - " + mArtist; } setTitle(titleLabel); mLoadingStartTime = System.currentTimeMillis(); mLoadingLastUpdateTime = System.currentTimeMillis(); mLoadingKeepGoing = true; mProgressDialog = new ProgressDialog(SpeechEdEditActivity.this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle(R.string.progress_dialog_loading); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mLoadingKeepGoing = false; } }); mProgressDialog.show(); final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() { public boolean reportProgress(double fractionComplete) { long now = System.currentTimeMillis(); if (now - mLoadingLastUpdateTime > 100) { mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete)); mLoadingLastUpdateTime = now; } return mLoadingKeepGoing; } }; // Create the MediaPlayer in a background thread mCanSeekAccurately = false; new Thread() { public void run() { mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE)); System.out.println("Seek test done, creating media player."); try { MediaPlayer player = new MediaPlayer(); player.setDataSource(mFile.getAbsolutePath()); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.prepare(); mPlayer = player; } catch (final java.io.IOException e) { Runnable runnable = new Runnable() { public void run() { handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); } ; } }.start(); // Load the sound file in a background thread new Thread() { public void run() { try { mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener); if (mSoundFile == null) { mProgressDialog.dismiss(); String name = mFile.getName().toLowerCase(); String[] components = name.split("\\."); String err; if (components.length < 2) { err = getResources().getString(R.string.no_extension_error); } else { err = getResources().getString(R.string.bad_extension_error) + " " + components[components.length - 1]; } final String finalErr = err; Runnable runnable = new Runnable() { public void run() { handleFatalError("UnsupportedExtension", finalErr, new Exception()); } }; mHandler.post(runnable); return; } } catch (final Exception e) { mProgressDialog.dismiss(); e.printStackTrace(); mInfo.setText(e.toString()); Runnable runnable = new Runnable() { public void run() { handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); return; } mProgressDialog.dismiss(); if (mLoadingKeepGoing) { Runnable runnable = new Runnable() { public void run() { finishOpeningSoundFile(); } }; mHandler.post(runnable); } else { SpeechEdEditActivity.this.finish(); } } }.start(); }
From source file:com.ringdroid.RingdroidEditActivity.java
private void loadFromFile() { mFile = new File(mFilename); mExtension = getExtensionFromFilename(mFilename); SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename); mTitle = metadataReader.mTitle;// w w w . j a v a 2 s . c o m mArtist = metadataReader.mArtist; mAlbum = metadataReader.mAlbum; mYear = metadataReader.mYear; mGenre = metadataReader.mGenre; String titleLabel = mTitle; if (mArtist != null && mArtist.length() > 0) { titleLabel += " - " + mArtist; } setTitle(Utils.convertGBK(titleLabel)); mLoadingStartTime = System.currentTimeMillis(); mLoadingLastUpdateTime = System.currentTimeMillis(); mLoadingKeepGoing = true; mProgressDialog = new ProgressDialog(RingdroidEditActivity.this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle(R.string.progress_dialog_loading); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mLoadingKeepGoing = false; } }); mProgressDialog.show(); final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() { public boolean reportProgress(double fractionComplete) { long now = System.currentTimeMillis(); if (now - mLoadingLastUpdateTime > 100) { mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete)); mLoadingLastUpdateTime = now; } return mLoadingKeepGoing; } }; // Create the MediaPlayer in a background thread mCanSeekAccurately = false; new Thread() { public void run() { mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE)); System.out.println("Seek test done, creating media player."); try { MediaPlayer player = new MediaPlayer(); player.setDataSource(mFile.getAbsolutePath()); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.prepare(); mPlayer = player; } catch (final java.io.IOException e) { Runnable runnable = new Runnable() { public void run() { handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); } ; } }.start(); // Load the sound file in a background thread new Thread() { public void run() { try { mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener); if (mSoundFile == null) { String name = mFile.getName().toLowerCase(); String[] components = name.split("\\."); String err; if (components.length < 2) { err = getResources().getString(R.string.no_extension_error); } else { err = getResources().getString(R.string.bad_extension_error) + " " + components[components.length - 1]; } final String finalErr = err; Runnable runnable = new Runnable() { public void run() { mProgressDialog.dismiss(); handleFatalError("UnsupportedExtension", finalErr, new Exception()); } }; mHandler.post(runnable); return; } } catch (final Exception e) { e.printStackTrace(); Runnable runnable = new Runnable() { public void run() { mProgressDialog.dismiss(); mInfo.setText(e.toString()); handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); return; } mHandler.post(new Runnable() { @Override public void run() { mProgressDialog.dismiss(); } }); if (mLoadingKeepGoing) { Runnable runnable = new Runnable() { public void run() { finishOpeningSoundFile(); } }; mHandler.post(runnable); } else { RingdroidEditActivity.this.finish(); } } }.start(); }
From source file:mp.teardrop.PlaybackService.java
/** * Returns a new MediaPlayer object/* w ww . java 2 s .c o m*/ */ private MediaPlayer getNewMediaPlayer() { MediaPlayer mp = new MediaPlayer(); mp.setAudioStreamType(AudioManager.STREAM_MUSIC); mp.setOnCompletionListener(this); mp.setOnErrorListener(this); mp.setOnPreparedListener(this); return mp; }