Example usage for android.media MediaPlayer release

List of usage examples for android.media MediaPlayer release

Introduction

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

Prototype

public void release() 

Source Link

Document

Releases resources associated with this MediaPlayer object.

Usage

From source file:com.cw.litenote.note.NoteUi.java

public NoteUi(AppCompatActivity activity, ViewPager viewPager, int position) {

    System.out.println("NoteUi / constructor");
    pager = viewPager;/*from ww  w.  j  a  v a  2  s  .  c  o  m*/
    act = activity;
    mPosition = position;

    DB_page db_page = new DB_page(act, TabsHost.getCurrentPageTableId());
    setNotesCnt(db_page.getNotesCount(true));
    String pictureUri = db_page.getNotePictureUri(position, true);
    String linkUri = db_page.getNoteLinkUri(position, true);

    String tagStr = "current" + position + "pictureView";
    ViewGroup pictureGroup = (ViewGroup) pager.findViewWithTag(tagStr);

    if ((pictureGroup != null)) {
        setPictureView_listeners(act, pager, pictureUri, linkUri, pictureGroup);

        TextView picView_footer = (TextView) (pictureGroup.findViewById(R.id.image_footer));

        Button picView_back_button = (Button) (pictureGroup.findViewById(R.id.image_view_back));
        Button picView_viewMode_button = (Button) (pictureGroup.findViewById(R.id.image_view_mode));

        TextView videoView_currPosition = (TextView) (pictureGroup.findViewById(R.id.video_current_pos));
        SeekBar videoView_seekBar = (SeekBar) (pictureGroup.findViewById(R.id.video_seek_bar));
        TextView videoView_fileLength = (TextView) (pictureGroup.findViewById(R.id.video_file_length));

        // show back button
        if (Note.isPictureMode())
            picView_back_button.setVisibility(View.VISIBLE);
        else
            picView_back_button.setVisibility(View.GONE);

        // Show picture title
        TextView picView_title;
        picView_title = (TextView) (pictureGroup.findViewById(R.id.image_title));
        String pictureName;
        if (!Util.isEmptyString(pictureUri))
            pictureName = Util.getDisplayNameByUriString(pictureUri, act);
        else if (Util.isYouTubeLink(linkUri))
            pictureName = linkUri;
        else
            pictureName = "";

        if (!Util.isEmptyString(pictureName)) {
            picView_title.setVisibility(View.VISIBLE);
            picView_title.setText(pictureName);
        } else
            picView_title.setVisibility(View.INVISIBLE);

        // show footer
        if (Note.isPictureMode()) {
            picView_footer.setVisibility(View.VISIBLE);
            picView_footer.setText((pager.getCurrentItem() + 1) + "/" + pager.getAdapter().getCount());
        } else
            picView_footer.setVisibility(View.GONE);

        // for video
        if (UtilVideo.hasVideoExtension(pictureUri, act)) {
            if (!UtilVideo.hasMediaControlWidget)
                NoteUi.updateVideoPlayButtonState(pager, getFocus_notePos());
            else
                show_picViewUI_previous_next(false, 0);
        }

        // set image view buttons (View Mode, Previous, Next) visibility
        if (Note.isPictureMode()) {
            picView_viewMode_button.setVisibility(View.VISIBLE);

            // show previous/next buttons for image, not for video
            if (UtilVideo.hasVideoExtension(pictureUri, act) && !UtilVideo.hasMediaControlWidget) // for video
            {
                System.out.println("NoteUi / constructor / for video");
                show_picViewUI_previous_next(true, position);
            } else if (UtilImage.hasImageExtension(pictureUri, act) && (UtilVideo.mVideoView == null))// for image
            {
                System.out.println("NoteUi / constructor / for image");
                show_picViewUI_previous_next(true, position);
            }
        } else {
            show_picViewUI_previous_next(false, 0);
            picView_viewMode_button.setVisibility(View.GONE);
        }

        // show seek bar for video only
        if (!UtilVideo.hasMediaControlWidget) {
            if (UtilVideo.hasVideoExtension(pictureUri, act)) {
                MediaPlayer mp = MediaPlayer.create(act, Uri.parse(pictureUri));

                if (mp != null) {
                    videoFileLength_inMilliSeconds = mp.getDuration();
                    mp.release();
                }

                primaryVideoSeekBarProgressUpdater(pager, position, UtilVideo.mPlayVideoPosition, pictureUri);
            } else {
                videoView_currPosition.setVisibility(View.GONE);
                videoView_seekBar.setVisibility(View.GONE);
                videoView_fileLength.setVisibility(View.GONE);
            }
        }

        showSeekBarProgress = true;
    }
}

From source file:com.polyvi.xface.extension.capture.MediaType.java

/**
 *  audio  video ./*ww w  . j ava 2s.c  o  m*/
 *
 * @param fileAbsPath ?
 * @param obj ?
 * @param isVideo ? video
 * @return ? JSONObject
 * @throws JSONException
 */
private JSONObject getAudioVideoData(String fileAbsPath, JSONObject obj, boolean isVideo) throws JSONException {
    MediaPlayer player = new MediaPlayer();
    try {
        player.setDataSource(fileAbsPath);
        player.prepare();
        obj.put(PROP_DURATION, player.getDuration() / XConstant.MILLISECONDS_PER_SECOND);
        if (isVideo) {
            obj.put(PROP_HEIGHT, player.getVideoHeight());
            obj.put(PROP_WIDTH, player.getVideoWidth());
        }
    } catch (IOException e) {
        XLog.e(CLASS_NAME, "Error: loading video file");
    }
    player.release();
    return obj;
}

From source file:com.android.onemedia.playback.LocalRenderer.java

@Override
public void setNextContent(Bundle request) {
    String source = request.getString(RequestUtils.EXTRA_KEY_SOURCE);
    Map<String, String> headers = null; // request.mHeaders;

    // TODO support video

    if (DEBUG) {/*from w  w w  . j a  va 2s . c  o m*/
        Log.d(TAG, mDebugId + ": Setting next content. Have player? " + (mPlayer != null)
                + " have next player? " + (mNextPlayer != null));
    }

    if (mPlayer == null) {
        // The manager isn't being used to play anything, don't try to
        // set a next.
        return;
    }
    if (mNextPlayer != null) {
        // Before setting up the new one clear out the old one and release
        // it to ensure it doesn't play.
        mPlayer.setNextMediaPlayer(null);
        mNextPlayer.release();
        mNextPlayer = null;
        mNextContent = null;
    }
    if (source == null) {
        // If there's no new content we're done
        return;
    }
    final MediaPlayer newPlayer = new MediaPlayer();

    try {
        if (headers != null) {
            Uri sourceUri = Uri.parse(source);
            newPlayer.setDataSource(mContext, sourceUri, headers);
        } else {
            newPlayer.setDataSource(source);
        }
    } catch (Exception e) {
        newPlayer.release();
        // Don't return an error until we get to this item in playback
        return;
    }

    if (preparePlayer(newPlayer, false)) {
        mPlayer.setNextMediaPlayer(newPlayer);
        mNextPlayer = newPlayer;
        mNextContent = new PlayerContent(source, headers);
    }
}

From source file:de.bogutzky.psychophysiocollector.app.MainActivity.java

private void playSound(int soundID) {
    MediaPlayer mediaPlayer = MediaPlayer.create(this, soundID);
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override//w w w  .ja va 2s.  c  o  m
        public void onCompletion(MediaPlayer mp) {
            mp.release();
        }
    });
    mediaPlayer.start();
}

From source file:de.azapps.mirakel.helper.TaskDialogHelpers.java

public static void playbackFile(final Activity context, final FileMirakel file, final boolean loud) {
    final MediaPlayer mPlayer = new MediaPlayer();
    final AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    if (!loud) {//w w w. j  a v a2s .c  o  m
        am.setSpeakerphoneOn(false);
        am.setMode(AudioManager.MODE_IN_CALL);
        context.setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
    }
    try {
        mPlayer.reset();
        if (!loud) {
            mPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
        }
        mPlayer.setDataSource(file.getFileStream(context).getFD());
        mPlayer.prepare();
        mPlayer.start();
        mPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(final MediaPlayer mp) {
                audio_playback_dialog.dismiss();
            }
        });
        am.setMode(AudioManager.MODE_NORMAL);
        audio_playback_playing = true;
    } catch (final IOException e) {
        Log.e(TAG, "prepare() failed");
    }
    audio_playback_dialog = new AlertDialog.Builder(context).setTitle(R.string.audio_playback_title)
            .setPositiveButton(R.string.audio_playback_pause, null)
            .setNegativeButton(R.string.audio_playback_stop, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    mPlayer.release();
                }
            }).setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(final DialogInterface dialog) {
                    mPlayer.release();
                    dialog.cancel();
                }
            }).create();
    audio_playback_dialog.setOnShowListener(new OnShowListener() {
        @Override
        public void onShow(final DialogInterface dialog) {
            final Button button = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
                    if (audio_playback_playing) {
                        button.setText(R.string.audio_playback_play);
                        mPlayer.pause();
                        audio_playback_playing = false;
                    } else {
                        button.setText(R.string.audio_playback_pause);
                        mPlayer.start();
                        audio_playback_playing = true;
                    }
                }
            });
        }
    });
    audio_playback_dialog.show();
}

From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java

public static boolean validateUrl(String url) {

    if (!URLUtil.isHttpUrl(url) && !URLUtil.isHttpsUrl(url)) {
        //if (LOCAL_LOGV) log("not a valid http or https url", "v");
        return false;
    }//from  www . j av  a 2 s . c  om
    //check for empty after prefix
    if (url.equals("http://") || url.equals("https://")) {
        return false;
    }

    MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        mediaPlayer.setDataSource(url);
        mediaPlayer.release();
    } catch (IOException e) {
        return false;
    }
    return true;
}

From source file:com.saulcintero.moveon.services.MoveOnService.java

private void playSound(int id) {
    switch (id) {
    case 1://from   www  .  j  a  va 2  s  .  c  o m
        mMediaPlayer = MediaPlayer.create(this, R.raw.beep);
        break;
    case 2:
        mMediaPlayer = MediaPlayer.create(this, R.raw.coach_whistle);
        break;
    }

    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });

    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mp.stop();
            mp.release();
        }
    });
}

From source file:org.sirimangalo.meditationplus.ActivityMain.java

private void populateChat(JSONArray chats, boolean admin) {
    if (findViewById(R.id.chat_list) == null)
        return;//from  w ww .j  a  va2s. c  om
    chatList = (ListView) findViewById(R.id.chat_list);

    int newChatNo = 0;

    int latestChatTime = 0;
    ArrayList<JSONObject> chatArray = new ArrayList<JSONObject>();

    if (chats.length() < lastChatArray.size()) { // prepend old chats
        for (int i = chats.length(); i < lastChatArray.size(); i++) {
            chatArray.add(lastChatArray.get(i));
        }
    }

    for (int i = 0; i < chats.length(); i++) {
        try {
            JSONObject chat = chats.getJSONObject(i);
            latestChatTime = Integer.parseInt(chat.getString("time"));
            if (latestChatTime > lastChatTime)
                newChatNo++;

            chatArray.add(chat);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    lastChatArray = chatArray;

    if (latestChatTime < lastChatTime)
        newChatNo = -1;

    if (admin)
        chatList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                String cid = (String) view.findViewById(R.id.message).getTag();
                ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                doSubmit("delchat_" + cid, nvp, true);
                return true;
            }
        });

    // save index and top position
    int index = chatList.getFirstVisiblePosition();
    View v = chatList.getChildAt(0);
    int top = (v == null) ? 0 : v.getTop();

    AdapterChat adapter = new AdapterChat(this, R.layout.list_item_chat, chatArray);
    chatList.setAdapter(adapter);

    // restore index and position

    if (doChatScroll) {
        chatList.setSelection(adapter.getCount() - 1);
        doChatScroll = false;
    } else
        chatList.setSelectionFromTop(index, top);

    if (newChatNo > 0) {
        if (currentPosition != 1 && lastChatTime > 0) {
            final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.tick);
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    mp.release();
                }
            });
            mp.start();
            newChats = true;
            ActionBar actionBar = getSupportActionBar();
            if (actionBar.getTabAt(1) != null)
                actionBar.getTabAt(1).setText(
                        Html.fromHtml(getString(R.string.title_section2).toUpperCase(Locale.getDefault()) + " ("
                                + newChatNo + ")"));
        }
    }
    lastChatTime = latestChatTime;
}

From source file:com.insthub.O2OMobile.Activity.C1_PublishOrderActivity.java

/**
 * ?/* www . j ava2 s. c o m*/
 */
private void stopRecording() {
    if (mTimer != null) {
        mTimer.cancel(); //??
    }
    mTimer = null;
    if (mRecorder != null) {
        try {
            mRecorder.stop();
            mRecorder.reset();
            mRecorder.release();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }
    mRecorder = null;

    MediaPlayer mp = MediaPlayer.create(this, Uri.parse(mFileName));
    if (null != mp) {
        int duration = mp.getDuration();//? ms
        if (duration > 3000) {
            mVoice.setVisibility(View.GONE);
            mVoicePlay.setVisibility(View.VISIBLE);
            mVoiceReset.setVisibility(View.VISIBLE);
        } else {
            ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                    getString(R.string.record_time_too_short));
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            File file = new File(newFileName());
            if (file.exists()) {
                file.delete();
            }
        }
        mp.release();
    }
    mVoice.setKeepScreenOn(false);
}

From source file:com.sentaroh.android.TaskAutomation.TaskExecutor.java

final static public void playBackMusic(TaskManagerParms taskMgrParms, EnvironmentParms envParms,
        CommonUtilities util, TaskResponse taskResponse, ActionResponse ar, String action, String dlg_id,
        String fp, String vol_left, String vol_right) {
    ar.action_resp = ActionResponse.ACTION_SUCCESS;
    File lf = new File(fp);
    if (!lf.exists()) {
        ar.action_resp = ActionResponse.ACTION_ERROR;
        ar.resp_msg_text = String.format(taskMgrParms.teMsgs.msgs_thread_task_play_sound_notfound, fp);
        return;//from   w  w  w  .j a v  a 2  s  .com
    }
    if (!isRingerModeNormal(envParms)) {
        ar.action_resp = ActionResponse.ACTION_WARNING;
        ar.resp_msg_text = taskMgrParms.teMsgs.msgs_thread_task_exec_ignore_sound_ringer_not_normal;
        return;
    }
    MediaPlayer player = MediaPlayer.create(taskMgrParms.context, Uri.parse(fp));
    taskResponse.active_action_name = action;

    if (player != null) {
        int duration = player.getDuration();
        TaskManager.showMessageDialog(taskMgrParms, envParms, util, taskResponse.active_group_name,
                taskResponse.active_task_name, taskResponse.active_action_name, taskResponse.active_dialog_id,
                MESSAGE_DIALOG_MESSAGE_TYPE_SOUND, fp);

        if (!vol_left.equals("-1") && !vol_left.equals(""))
            player.setVolume(Float.valueOf(vol_left) / 100, Float.valueOf(vol_right) / 100);
        player.start();
        waitTimeTc(taskResponse, duration + 10);
        if (!taskResponse.active_thread_ctrl.isEnable()) {
            ar.action_resp = ActionResponse.ACTION_CANCELLED;
            ar.resp_msg_text = "Action was cancelled";
        }
        player.stop();
        player.release();
        TaskManager.closeMessageDialog(taskMgrParms, envParms, util, taskResponse);
    } else {
        ar.action_resp = ActionResponse.ACTION_ERROR;
        ar.resp_msg_text = String.format(taskMgrParms.teMsgs.msgs_thread_task_play_sound_error, fp);
    }
}