Example usage for android.media MediaPlayer prepare

List of usage examples for android.media MediaPlayer prepare

Introduction

In this page you can find the example usage for android.media MediaPlayer prepare.

Prototype

public void prepare() throws IOException, IllegalStateException 

Source Link

Document

Prepares the player for playback, synchronously.

Usage

From source file:mp.teardrop.PlaybackService.java

public void prepareMediaPlayer(MediaPlayer mp, Song song) throws IOException {

    Date threeHoursAgo = new Date(new Date().getTime() - 10800000);

    if (song.isCloudSong
            && (song.dropboxLinkCreated == null || song.dropboxLinkCreated.before(threeHoursAgo))) {
        //FIXME some of this code is duplicated
        try {//  ww  w  . j a v  a 2 s .co  m
            String path = LibraryActivity.mApi.media(song.dbPath, true).url;
            song.path = path;
            song.dropboxLinkCreated = new Date();
        } catch (DropboxException e1) {
            Log.w("OrchidMP", "Failed to refresh a song's streaming link: " + e1.getMessage());
            throw new IOException("Failed to refresh a song's streaming link.");
        }
    }

    mp.setDataSource(song.path);

    synchronized (sDurationRefreshLock) {
        mp.prepare();
    }

    //TODO what is this and why is it here but not in newer Vanilla versions?
    //      Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
    //      intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, mp.getAudioSessionId());
    //      intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
    //      sendBroadcast(intent);

    applyReplayGain(mp, song);
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

private boolean prepareAudio(File audioFile, final AudioContentViewControl view, final long messageId) {
    stopMediaPlayerUpdater();//from  ww  w .j  ava  2 s  .c  om
    try {
        AudioFragment audio = getAudioFragment();
        final MediaPlayer player = audio.getPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(audioFile.getAbsolutePath());
        player.prepare();

        // prepare was successful
        audio.setMessageId(messageId);
        mAudioControl = view;

        view.prepare(player.getDuration());
        player.seekTo(view.getPosition());
        view.setProgressChangeListener(true);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopMediaPlayerUpdater();
                view.end();
                AudioFragment audio = findAudioFragment();
                if (audio != null)
                    audio.seekPlayerTo(0);
                setAudioStatus(AudioContentView.STATUS_ENDED);
            }
        });
        return true;
    } catch (IOException e) {
        Toast.makeText(getActivity(), R.string.err_file_not_found, Toast.LENGTH_SHORT).show();
        return false;
    }
}

From source file:net.nightwhistler.pageturner.fragment.ReadingFragment.java

public void onStreamingCompleted(final String wavFile) {

    LOG.debug("TTS streaming completed for " + wavFile);

    if (!ttsIsRunning()) {
        this.textToSpeech.stop();
        return;// w w  w  .j  av  a2  s. c  om
    }

    if (!ttsItemPrep.containsKey(wavFile)) {
        LOG.error(
                "Got onStreamingCompleted for " + wavFile + " but there is no corresponding TTSPlaybackItem!");
        return;
    }

    final TTSPlaybackItem item = ttsItemPrep.remove(wavFile);

    try {

        MediaPlayer mediaPlayer = item.getMediaPlayer();
        mediaPlayer.reset();
        mediaPlayer.setDataSource(wavFile);
        mediaPlayer.prepare();

        this.ttsPlaybackItemQueue.add(item);

    } catch (Exception e) {
        LOG.error("Could not play", e);
        showTTSFailed(e.getLocalizedMessage());
        return;
    }

    this.uiHandler.post(this::closeWaitDialog);

    //If the queue is size 1, it only contains the player we just added,
    //meaning this is a first playback start.
    if (ttsPlaybackItemQueue.size() == 1) {
        startPlayback();
    }
}

From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java

@Override
public void onUtteranceCompleted(final String wavFile) {

    LOG.debug("TTS streaming completed for " + wavFile);

    if (!ttsIsRunning()) {
        this.textToSpeech.stop();
        return;// w ww .  j a v a2 s.  com
    }

    if (!ttsItemPrep.containsKey(wavFile)) {
        LOG.error(
                "Got onUtteranceCompleted for " + wavFile + " but there is no corresponding TTSPlaybackItem!");
        return;
    }

    final TTSPlaybackItem item = ttsItemPrep.remove(wavFile);

    try {

        MediaPlayer mediaPlayer = item.getMediaPlayer();
        mediaPlayer.reset();
        mediaPlayer.setDataSource(wavFile);
        mediaPlayer.prepare();

        this.ttsPlaybackItemQueue.add(item);

    } catch (Exception e) {
        LOG.error("Could not play", e);
        showTTSFailed(e.getLocalizedMessage());
        return;
    }

    this.uiHandler.post(new Runnable() {

        @Override
        public void run() {
            closeWaitDialog();
        }
    });

    //If the queue is size 1, it only contains the player we just added,
    //meaning this is a first playback start.
    if (ttsPlaybackItemQueue.size() == 1) {
        startPlayback();
    }
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

@Override
public void onUtteranceCompleted(final String wavFile) {

    LOG.debug("TTS streaming completed for " + wavFile);

    if (!ttsIsRunning()) {
        this.textToSpeech.stop();
        return;/*  ww  w.  j  a  va2 s .c  o m*/
    }

    if (!ttsItemPrep.containsKey(wavFile)) {
        LOG.error(
                "Got onUtteranceCompleted for " + wavFile + " but there is no corresponding TTSPlaybackItem!");
        return;
    }

    final TTSPlaybackItem item = ttsItemPrep.remove(wavFile);

    try {

        MediaPlayer mediaPlayer = item.getMediaPlayer();
        mediaPlayer.reset();
        mediaPlayer.setDataSource(wavFile);
        mediaPlayer.prepare();

        this.ttsPlaybackItemQueue.add(item);

    } catch (Exception e) {
        LOG.error("Could not play", e);
        showTTSFailed(e.getLocalizedMessage());
        return;
    }

    this.uiHandler.post(new Runnable() {

        @Override
        public void run() {
            closeWaitDialog();
        }
    });

    // If the queue is size 1, it only contains the player we just added,
    // meaning this is a first playback start.
    if (ttsPlaybackItemQueue.size() == 1) {
        startPlayback();
    }
}

From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java

private void playBeep(boolean error) {

    if (!isAdded()) {
        return;//  ww w.  j a  v a 2 s .c om
    }

    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.aujur.ebookreader.activity.ReadingFragment.java

private void playBeep(boolean error) {

    if (!isAdded()) {
        return;/*from   ww  w  . jav  a  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:org.telegram.ui.ChatActivity.java

private void stopRecording() {
    try {// ww  w  .java  2 s  . co  m
        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.nest5.businessClient.Initialactivity.java

public void playSound(Context context)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    MediaPlayer mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setDataSource(context, soundUri);
    final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mMediaPlayer.setLooping(false);//  w w  w.java  2 s . c om
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    }
}

From source file:com.tct.mail.compose.ComposeActivity.java

protected void sendOrSave(final boolean save, final boolean showToast) {
    // Check if user is a monkey. Monkeys can compose and hit send
    // button but are not allowed to send anything off the device.
    // TS: xiaolin.li 2015-01-08 EMAIL BUGFIX-893877 DEL_S
    /*if (ActivityManager.isUserAMonkey()) {
    return;/*www  . j  a v  a 2  s.  c  om*/
    }*/
    // TS: xiaolin.li 2015-01-08 EMAIL BUGFIX-893877 DEL_E
    final SendOrSaveCallback callback = new SendOrSaveCallback() {
        // FIXME: unused
        private int mRestoredRequestId;

        @Override
        public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
            synchronized (mActiveTasks) {
                int numTasks = mActiveTasks.size();
                if (numTasks == 0) {
                    // Start service so we won't be killed if this app is
                    // put in the background.
                    startService(new Intent(ComposeActivity.this, EmptyService.class));
                }

                mActiveTasks.add(sendOrSaveTask);
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
            }
        }

        @Override
        public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message) {
            synchronized (mDraftLock) {
                mDraftAccount = sendOrSaveMessage.mAccount;
                mDraftId = message.id;
                mDraft = message;
                if (sRequestMessageIdMap != null) {
                    sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
                }
                // Cache request message map, in case the process is killed
                saveRequestMap();
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
            }
        }

        @Override
        public Message getMessage() {
            synchronized (mDraftLock) {
                return mDraft;
            }
        }

        @Override
        public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
            // Update the last sent from account.
            if (mAccount != null) {
                MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
            }
            // TS: zhaotianyong 2015-03-25 EMAIL BUGFIX-954496 ADD_S
            // TS: zhaotianyong 2015-03-31 EMAIL BUGFIX-963249 ADD_S
            if (doSend) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) ComposeActivity.this
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
                if (info == null) {
                    Utility.showToast(ComposeActivity.this, R.string.send_failed);
                }
            }
            // TS: zhaotianyong 2015-03-31 EMAIL BUGFIX-963249 ADD_E
            // TS: zhaotianyong 2015-03-25 EMAIL BUGFIX-954496 ADD_E
            if (success) {
                // Successfully sent or saved so reset change markers
                discardChanges();
                //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 ADD_S
                if (!doSend && showToast) {
                    Intent intent = new Intent(DRAFT_SAVED_ACTION);
                    intent.setPackage(getString(R.string.email_package_name));
                    intent.putExtra(BaseColumns._ID, mDraftId);
                    //send ordered broadcast to execute the event in sequence in different receivers,
                    //ordered by priority
                    sendOrderedBroadcast(intent, null);
                }
                //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 ADD_E
            } else {
                // A failure happened with saving/sending the draft
                // TODO(pwestbro): add a better string that should be used
                // when failing to send or save
                //[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,08/05/2016,2635083
                Utility.showShortToast(ComposeActivity.this, R.string.send_failed);
                //Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
                //        .show();
            }

            int numTasks;
            synchronized (mActiveTasks) {
                // Remove the task from the list of active tasks
                mActiveTasks.remove(task);
                numTasks = mActiveTasks.size();
            }

            if (numTasks == 0) {
                // Stop service so we can be killed.
                stopService(new Intent(ComposeActivity.this, EmptyService.class));
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
            }
        }

        @Override
        public void incrementRecipientsTimesContacted(final List<String> recipients) {
            ComposeActivity.this.incrementRecipientsTimesContacted(recipients);
        }
    };
    //TS: zheng.zou 2015-3-16 EMAIL BUGFIX_948927 Mod_S
    if (mReplyFromAccount == null && mAccount != null) {
        mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
    }
    if (mReplyFromAccount != null) {
        setAccount(mReplyFromAccount.account);
    }
    //TS: zheng.zou 2015-3-16 EMAIL BUGFIX_948927 Mod_E
    // TS: yanhua.chen 2015-9-19 EMAIL BUGFIX_569665 ADD_S
    mIsSaveDraft = save;
    // TS: yanhua.chen 2015-9-19 EMAIL BUGFIX_569665 ADD_E

    final Spanned body = removeComposingSpans(mBodyView.getText());
    SEND_SAVE_TASK_HANDLER.post(new Runnable() {
        @Override
        public void run() {
            final Message msg = createMessage(mReplyFromAccount, mRefMessage, getMode(), body);
            // TS: kaifeng.lu 2016-4-6 EMAIL BUGFIX_1909143 ADD_S
            if (/*!mIsClickIcon &&*/ !mEditDraft && (mIsSaveDraft || doSend)) {//[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,05/06/2016,2013535
                String body1 = mBodyView.getText().toString().replace("\n", "\n\r");
                SpannableString spannableString = new SpannableString(body1);
                StringBuffer bodySignature = new StringBuffer(body1);
                //[BUGFIX]-DEL begin by SCDTABLET.shujing.jin@tcl.com,05/17/2016,2013535,2148647
                //if(mCachedSettings != null){
                //    bodySignature.append(convertToPrintableSignature(mCachedSettings.signature));
                //}
                //[BUGFIX]-DEL end by SCDTABLET.shujing.jin
                spannableString = new SpannableString(bodySignature.toString());
                msg.bodyHtml = spannedBodyToHtml(spannableString, true);
                msg.bodyText = bodySignature.toString();
            }
            // TS: kaifeng.lu 2016-4-6 EMAIL BUGFIX_1909143 ADD_E
            mRequestId = sendOrSaveInternal(ComposeActivity.this, mReplyFromAccount, msg, mRefMessage,
                    mQuotedTextView.getQuotedTextIfIncluded(), callback, SEND_SAVE_TASK_HANDLER, save,
                    mComposeMode, mDraftAccount, mExtraValues);
        }
    });

    // Don't display the toast if the user is just changing the orientation,
    // but we still need to save the draft to the cursor because this is how we restore
    // the attachments when the configuration change completes.
    if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
        //TS: xinlei.sheng 2015-01-26 EMAIL FIXBUG_886976 MOD_S
        if (mLaunchContact) {
            mLaunchContact = false;
        } else {
            //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 MDD_S
            if (!save) {
                //[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,08/05/2016,2635083
                Utility.showToast(this, R.string.sending_message);
                //Toast.makeText(this, R.string.sending_message,
                //        Toast.LENGTH_LONG).show();
            }
            //                Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
            //                        Toast.LENGTH_LONG).show();
            //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 MOD_E
        }
        //TS: xinlei.sheng 2015-01-26 EMAIL FIXBUG_886976 MOD_E
    }

    // Need to update variables here because the send or save completes
    // asynchronously even though the toast shows right away.
    discardChanges();
    updateSaveUi();

    // If we are sending, finish the activity
    if (!save) {
        finish();
        //TS: yanhua.chen 2015-6-15 EMAIL BUGFIX_1024081 ADD_S
        //TS: lin-zhou 2015-10-15 EMAIL BUGFIX_718388 MOD_S
        Uri soundUri = Uri.parse(
                "android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.email_sent);
        MediaPlayer player = new MediaPlayer();
        try {
            if (soundUri != null) {
                player.setDataSource(getApplicationContext(), soundUri);
            }
            player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            player.prepare();
            player.start();
        } catch (IllegalArgumentException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IllegalArgumentException");
        } catch (SecurityException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur SecurityException");
        } catch (IllegalStateException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IllegalStateException");
        } catch (IOException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IOException");
        } catch (NullPointerException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur NullPointerException");
        }
        //TS: lin-zhou 2015-10-15 EMAIL BUGFIX_718388 MOD_E
        //TS: yanhua.chen 2015-6-15 EMAIL BUGFIX_1024081 ADD_E
    }
}