Example usage for android.media MediaPlayer stop

List of usage examples for android.media MediaPlayer stop

Introduction

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

Prototype

public void stop() throws IllegalStateException 

Source Link

Document

Stops playback after playback has been started or paused.

Usage

From source file:org.cyanogenmod.theme.chooser.AudiblePreviewFragment.java

private void freeMediaPlayers() {
    final int N = mMediaPlayers.size();
    for (int i = 0; i < N; i++) {
        MediaPlayer mp = mMediaPlayers.get(mMediaPlayers.keyAt(i));
        if (mp != null) {
            mp.stop();
            mp.release();/*from ww w.j  a  v  a 2  s.c  om*/
        }
    }
    mMediaPlayers.clear();
}

From source file:it.interfree.leonardoce.bootreceiver.AlarmKlaxon.java

private void play() {
    // stop() checks to see if we are already playing.
    stop();/*from  ww w . j  av a  2 s . c o  m*/

    if (LOGV) {
        Log.v(LTAG, "AlarmKlaxon.play() ");
    }

    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    if (LOGV) {
        Log.v(LTAG, "Using default alarm: " + alert.toString());
    }

    // TODO: Reuse mMediaPlayer instead of creating a new one and/or use
    // RingtoneManager.
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setOnErrorListener(new OnErrorListener() {
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.e(LTAG, "Error occurred while playing audio.");
            mp.stop();
            mp.release();
            mMediaPlayer = null;
            return true;
        }
    });

    try {
        // Check if we are in a call. If we are, use the in-call alarm
        // resource at a low volume to not disrupt the call.
        mMediaPlayer.setDataSource(this, alert);
        startAlarm(mMediaPlayer);
    } catch (Exception ex) {
        Log.v(LTAG, "Non trovo la suoneria dell'allarme???");
    }

    /* Start the vibrator after everything is ok with the media player */
    mVibrator.vibrate(sVibratePattern, 0);
    mPlaying = true;
    mStartTime = System.currentTimeMillis();
    enableKiller();
}

From source file:com.google.dotorg.crisisresponse.translationcards.RecordingActivity.java

private void finishListening(MediaPlayer mediaPlayer) {
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.stop();
    }//from  w w w .  j  av a 2  s  .  co  m
    mediaPlayer.reset();
    mediaPlayer.release();
    recordButton.setBackgroundResource(R.drawable.button_record_enabled);
    listenButton.setBackgroundResource(R.drawable.button_listen_enabled);
    recordingStatus = RecordingStatus.RECORDED;
}

From source file:hku.fyp14017.blencode.ui.controller.SoundController.java

public void stopSound(MediaPlayer mediaPlayer, ArrayList<SoundInfo> soundInfoList) {
    if (isSoundPlaying(mediaPlayer)) {
        mediaPlayer.stop();
    }//  w w  w .j av a 2 s .c  om

    for (int i = 0; i < soundInfoList.size(); i++) {
        soundInfoList.get(i).isPlaying = false;
    }
}

From source file:de.madvertise.android.sdk.MadvertiseMraidView.java

public MadvertiseMraidView(Context context) {
    super(context);
    setVerticalScrollBarEnabled(false);//from   www .  j  av a  2s  .  c  om
    setHorizontalScrollBarEnabled(false);
    setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    setBackgroundColor(Color.TRANSPARENT);
    WebSettings settings = getSettings();
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    settings.setJavaScriptEnabled(true);
    //settings.setPluginsEnabled(true);

    // Initialize the default expand properties.
    DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
    mExpandProperties = new ExpandProperties(metrics.widthPixels, metrics.heightPixels);
    MadvertiseUtil.logMessage(null, Log.INFO,
            "Setting default expandProperties : " + mExpandProperties.toJson().toString());

    // This bridge stays available until this view is destroyed, hence no
    // reloading when displaying new ads is necessary.
    addJavascriptInterface(mBridge, "mraid_bridge");

    setWebViewClient(new WebViewClient() {
        private boolean mError = false;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            post(new Runnable() {
                @Override
                public void run() {
                    if (mListener != null) {
                        mListener.onAdClicked();
                    }
                    final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url),
                            getContext().getApplicationContext(), MadvertiseActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getContext().startActivity(intent);
                }
            });
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!url.endsWith("mraid.js") && !mError) {
                MadvertiseUtil.logMessage(null, Log.DEBUG, "Setting mraid to default");
                checkReady();

                // Close button in default size for interstitial ads
                if (mPlacementType == MadvertiseUtil.PLACEMENT_TYPE_INTERSTITIAL) {
                    mCloseButton = addCloseButtonToViewGroup(((ViewGroup) getParent()));
                    mCloseButton.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
                }
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mError = true;
        }
    });

    // Comment this in to enable video tag-capability.
    this.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            MadvertiseUtil.logMessage(null, Log.INFO, "showing VideoView");
            super.onShowCustomView(view, callback);
            if (view instanceof FrameLayout) {
                FrameLayout frame = (FrameLayout) view;
                if (frame.getFocusedChild() instanceof VideoView) {
                    mVideo = (VideoView) ((FrameLayout) view).getFocusedChild();
                    frame.removeView(mVideo);
                    ((ViewGroup) getParent()).addView(mVideo);

                    // Will also be called onError
                    mVideo.setOnCompletionListener(new OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer player) {
                            player.stop();
                        }
                    });

                    mVideo.setOnErrorListener(new OnErrorListener() {

                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            MadvertiseUtil.logMessage(null, Log.WARN, "Error while playing video");

                            if (mListener != null) {
                                mListener.onError(new IOException("Error while playing video"));
                            }

                            // We return false in order to call
                            // onCompletion()
                            return false;
                        }
                    });

                    mVideo.start();
                }
            }
        }

        @Override
        public void onHideCustomView() {
            if (mVideo != null) {
                ((ViewGroup) getParent()).removeView(mVideo);
                if (mVideo.isPlaying()) {
                    mVideo.stopPlayback();
                }
            }
        }
    });
}

From source file:de.baumann.thema.FragmentSound.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.sound, container, false);

    setHasOptionsMenu(true);/*from ww w. ja  v  a 2 s  .com*/

    final String[] itemTITLE = {
            "Ouverture - Hymne" + " (Steven Testelin)" + " | " + getString(R.string.duration) + " 01:49",
            "Canon and Gigue in D major" + " | " + getString(R.string.duration) + "  00:45",
            "Epic" + " (Alexey Anisimov)" + " | " + getString(R.string.duration) + "  01:53",
            "Isn't it" + " | " + getString(R.string.duration) + " 00:01",
            "Jingle Bells Sms" + " | " + getString(R.string.duration) + " 00:04",
            "Wet" + " | " + getString(R.string.duration) + " 00:01", };

    final String[] itemURL = {
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/hymne.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/canon.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/epic.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/isnt_it.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/jingle_bells_sms.mp3",
            Environment.getExternalStorageDirectory() + "/Android/data/de.baumann.thema/wet.mp3", };

    final String[] itemDES = { "CC license: https://www.jamendo.com/track/1004091/ouverture-hymne",
            "CC license: https://musopen.org/music/2672/johann-pachelbel/canon-and-gigue-in-d-major/",
            "CC license: https://www.jamendo.com/track/1344095/epic",
            "CC license: https://notificationsounds.com/standard-ringtones/isnt-it-524",
            "CC license: https://notificationsounds.com/message-tones/jingle-bells-sms-523",
            "CC license: https://notificationsounds.com/notification-sounds/wet-431", };

    final String[] itemFN = { "hymne.mp3", "canon.mp3", "epic.mp3", "isnt_it.mp3", "jingle_bells_sms.mp3",
            "wet.mp3", };

    CustomListAdapter_Sound adapter = new CustomListAdapter_Sound(getActivity(), itemTITLE, itemURL, itemDES,
            itemDES);
    listView = (ListView) rootView.findViewById(R.id.bookmarks);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            String Selecteditem = itemURL[+position];
            final MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(Selecteditem));
            mp.start();

            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    mp.stop();
                }
            }, 5000);
        }
    });

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            final String SelecteditemMes = itemTITLE[+position];
            final String Selecteditem = itemURL[+position];
            final String SelecteditemTitle = itemFN[+position];
            final String SelecteditemUrl = itemDES[+position].substring(12);
            final CharSequence[] options = { getString(R.string.set_ringtone),
                    getString(R.string.set_notification), getString(R.string.set_alarm),
                    getString(R.string.play), getString(R.string.open) };

            new AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {

                            if (options[item].equals(getString(R.string.set_ringtone))) {

                                File directory_al = new File(
                                        Environment.getExternalStorageDirectory() + "/Ringtones/");
                                if (!directory_al.exists()) {
                                    directory_al.mkdirs();
                                }

                                try {

                                    InputStream in;
                                    OutputStream out;
                                    in = new FileInputStream(Selecteditem);
                                    out = new FileOutputStream(Environment.getExternalStorageDirectory()
                                            + "/Ringtones/" + SelecteditemTitle);

                                    byte[] buffer = new byte[1024];
                                    int read;
                                    while ((read = in.read(buffer)) != -1) {
                                        out.write(buffer, 0, read);
                                    }
                                    in.close();

                                    // write the output file
                                    out.flush();
                                    out.close();

                                    MediaScannerConnection.scanFile(getActivity(),
                                            new String[] { Environment.getExternalStorageDirectory()
                                                    + "/Ringtones/" + SelecteditemTitle },
                                            null, new MediaScannerConnection.OnScanCompletedListener() {
                                                @Override
                                                public void onScanCompleted(String path, Uri uri) {
                                                    Intent intent2 = new Intent(Settings.ACTION_SOUND_SETTINGS);
                                                    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                    getActivity().startActivity(intent2);
                                                }
                                            });

                                } catch (Exception e) {
                                    Log.e("tag", e.getMessage());
                                }

                            } else if (options[item].equals(getString(R.string.set_notification))) {

                                File directory_al = new File(
                                        Environment.getExternalStorageDirectory() + "/Notifications/");
                                if (!directory_al.exists()) {
                                    directory_al.mkdirs();
                                }

                                try {

                                    InputStream in;
                                    OutputStream out;
                                    in = new FileInputStream(Selecteditem);
                                    out = new FileOutputStream(Environment.getExternalStorageDirectory()
                                            + "/Notifications/" + SelecteditemTitle);

                                    byte[] buffer = new byte[1024];
                                    int read;
                                    while ((read = in.read(buffer)) != -1) {
                                        out.write(buffer, 0, read);
                                    }
                                    in.close();

                                    // write the output file
                                    out.flush();
                                    out.close();

                                    MediaScannerConnection.scanFile(getActivity(),
                                            new String[] { Environment.getExternalStorageDirectory()
                                                    + "/Notifications/" + SelecteditemTitle },
                                            null, new MediaScannerConnection.OnScanCompletedListener() {
                                                @Override
                                                public void onScanCompleted(String path, Uri uri) {
                                                    Intent intent2 = new Intent(Settings.ACTION_SOUND_SETTINGS);
                                                    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                                    getActivity().startActivity(intent2);
                                                }
                                            });

                                } catch (Exception e) {
                                    Log.e("tag", e.getMessage());
                                }

                            } else if (options[item].equals(getString(R.string.set_alarm))) {

                                File directory_al = new File(
                                        Environment.getExternalStorageDirectory() + "/Alarms/");
                                if (!directory_al.exists()) {
                                    directory_al.mkdirs();
                                }

                                try {

                                    InputStream in;
                                    OutputStream out;
                                    in = new FileInputStream(Selecteditem);
                                    out = new FileOutputStream(Environment.getExternalStorageDirectory()
                                            + "/Alarms/" + SelecteditemTitle);

                                    byte[] buffer = new byte[1024];
                                    int read;
                                    while ((read = in.read(buffer)) != -1) {
                                        out.write(buffer, 0, read);
                                    }
                                    in.close();

                                    // write the output file
                                    out.flush();
                                    out.close();

                                    MediaScannerConnection.scanFile(getActivity(),
                                            new String[] { Environment.getExternalStorageDirectory()
                                                    + "/Alarms/" + SelecteditemTitle },
                                            null, new MediaScannerConnection.OnScanCompletedListener() {
                                                @Override
                                                public void onScanCompleted(String path, Uri uri) {
                                                    Snackbar.make(listView, R.string.set_alarm_suc,
                                                            Snackbar.LENGTH_LONG).show();
                                                }
                                            });

                                } catch (Exception e) {
                                    Log.e("tag", e.getMessage());
                                }

                                Snackbar.make(listView, getString(R.string.set_alarm_suc), Snackbar.LENGTH_LONG)
                                        .show();

                            } else if (options[item].equals(getString(R.string.play))) {
                                final MediaPlayer mp = MediaPlayer.create(getActivity(),
                                        Uri.parse(Selecteditem));

                                new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.play))
                                        .setMessage(SelecteditemMes).setPositiveButton(R.string.cancel,
                                                new DialogInterface.OnClickListener() {

                                                    public void onClick(DialogInterface dialog,
                                                            int whichButton) {
                                                        mp.stop();
                                                        dialog.cancel();
                                                    }
                                                })
                                        .setOnCancelListener(new DialogInterface.OnCancelListener() {
                                            @Override
                                            public void onCancel(DialogInterface dialog) {
                                                mp.stop();
                                                dialog.cancel();
                                            }
                                        }).show();
                                mp.start();
                            } else if (options[item].equals(getString(R.string.open))) {
                                Uri uri = Uri.parse(SelecteditemUrl); // missing 'http://' will cause crashed
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(intent);
                            }
                        }
                    }).show();
            return true;
        }
    });

    return rootView;
}

From source file:org.FrancoisDescamps.CatPlayer.MusicService.java

public void playMusic(final String pathToMusic) {
    //register receiver
    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    HeadphonesUnplugReceiver receiver = new HeadphonesUnplugReceiver();
    registerReceiver(receiver, receiverFilter);

    if (mp != null) {
        mp.stop();
        mp = null;/* ww  w . jav  a2  s.  c  o  m*/
    }

    try {
        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.setDataSource(pathToMusic);
        mp.prepare();
        mp.start();
    } catch (Exception e) {
        /*NOP*/
    }

    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            switch (repeat) {
            case 0: // Lecture en boucle dsactive
                /* NOP */
                break;
            case 1: // Lecture en boucle d'une seule musique
                playMusic(pathToMusic);
                break;
            case 2: // Lecture en boucle de toutes les musiques
                if (positionOfInitialMusic + cpt + 1 == queu.size()) {
                    cpt = 0;
                    positionOfInitialMusic = 0;
                } else {
                    cpt++;
                }
                playMusic(queu.get(positionOfInitialMusic + cpt).getPath());
                break;
            }

            currentTitle = properties[0][positionOfInitialMusic + cpt];
            currentAlbum = properties[1][positionOfInitialMusic + cpt];
            currentArtist = properties[2][positionOfInitialMusic + cpt];
            currentPath = properties[3][positionOfInitialMusic + cpt];

            musicAsChanged = true;
            MainActivity.notifyOtherMusicStarted();
            buildNotification(true);

            //save "cpt"
            editor = preferences.edit();
            editor.putInt("cpt", cpt);

            if (Build.VERSION.SDK_INT < 9) {
                editor.commit();
            } else {
                editor.apply();
            }
        }
    });
}

From source file:ui.GalleryFileActivity.java

private void doPlay() {
    recordBtn.setText("?");
    if (!TextUtils.isEmpty(voicePath)) {
        try {//from w w w  .  j  a v  a  2  s .  com
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mMediaPlayer.reset();
                mHandler.sendEmptyMessage(2);
                return;
            }
            if (mMediaPlayer == null) {
                mMediaPlayer = new MediaPlayer();
            }
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(voicePath);
            mMediaPlayer.prepare();

        } catch (Exception e) {
            e.printStackTrace();
        }
        mMediaPlayer.start();
        mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                int time = mp.getDuration() / 1000;
                voice_file.setText(Util.formatLongToTimeStr(time));
                mHandler.post(updateThread);
            }
        });
        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                mp.reset();
                mHandler.sendEmptyMessage(2);

            }
        });

        mMediaPlayer.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int arg1, int arg2) {
                mp.stop();
                mp.reset();
                mHandler.sendEmptyMessage(2);
                return false;
            }
        });
    }

}

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

private void playSound(int id) {
    switch (id) {
    case 1://from   www . ja v a  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: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   ww w.  j a  v a 2 s . c om
    }
    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);
    }
}