Example usage for android.media MediaPlayer start

List of usage examples for android.media MediaPlayer start

Introduction

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

Prototype

public void start() throws IllegalStateException 

Source Link

Document

Starts or resumes playback.

Usage

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();//from ww  w  . j  a v a  2 s.c  om
        mp = null;
    }

    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:ca.taglab.PictureFrame.ScreenSlidePageFragment.java

private void messageSent(View v) {
    switch (v.getId()) {
    case R.id.video:
        mConfirmation.setImageResource(R.drawable.confirm_red);
        break;/*www .j ava 2  s .  co m*/

    case R.id.photo:
        mConfirmation.setImageResource(R.drawable.confirm_blue);
        break;

    case R.id.audio:
        mConfirmation.setImageResource(R.drawable.confirm_green);
        break;

    case R.id.wave:
        mConfirmation.setImageResource(R.drawable.confirm_orange);
        break;
    }

    MediaPlayer mPlayer = MediaPlayer.create(getActivity().getApplicationContext(), R.raw.success_low);
    mPlayer.start();

    mConfirmation.setAlpha(0f);
    mConfirmation.setVisibility(View.VISIBLE);
    mConfirmation.animate().alpha(1f).setDuration(mLongAnimationDuration * 2)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    mConfirmation.animate().alpha(0f).setDuration(mLongAnimationDuration * 2)
                            .setListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    mConfirmation.setVisibility(View.GONE);
                                }
                            });
                }
            });

}

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 w w  w .  j a  va 2 s . c  o m*/

    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:com.sourceauditor.sahomemonitor.MainActivity.java

@Override
public void onPrepared(MediaPlayer mp) {
    if (!mp.isPlaying() && !pauseBeforePlaying) {
        try {/*ww w.j  a  v a2 s .c  om*/
            mp.start();
            this.playPauseButton.setText(getString(R.string.label_pause));
        } catch (Exception e) {
            Log.e(TAG, "Error trying to start media player: " + e.getMessage());
        }
    }
}

From source file:com.rainmakerlabs.bleepsample.BleepService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand");
    String actionName = intent.getStringExtra("actionName");
    if (intent == null || intent.getExtras() == null) {//just removing these checks
    } else if (actionName.equalsIgnoreCase(BLEepService.INTENT_BLEEP_PROCESS)
            && intent.getExtras().containsKey(BLEepService.INTENT_BLEEP_PASSED_LIST)) {
        ArrayList<Bleep> bleeps = (ArrayList<Bleep>) intent.getExtras()
                .getSerializable(BLEepService.INTENT_BLEEP_PASSED_LIST);
        for (final Bleep bleep : bleeps) {
            String msgType = bleep.getType();
            String atts = bleep.getAtts();
            try {
                JSONObject objMsg = new JSONObject(atts);
                //thisBleepService.addExtraLog(bleep, "FEEDBACK", "good");//use this when you want to send a custom log to BMS. for instance, you could display a feedback dialog, and ask users to give a rating, and BMS will help you collate the information. put this where necessary, it's just here for example
                Log.d(TAG, "Message Received of Type: " + msgType);
                if (msgType.equalsIgnoreCase("image")) {
                    final String strImgUrl = objMsg.optString(APIKeyDefineCommand.MSG_IMG);
                    final String adAspect = objMsg.optString(APIKeyDefineCommand.MSG_IMGASP);
                    String strImgMsgTemp = objMsg.optString(APIKeyDefineCommand.MSG_NOTIF);
                    //putting the default message above would only work for missing key, not in case of empty string. empty string will prevent the notification, so fix below
                    if (strImgMsgTemp.equalsIgnoreCase(""))
                        strImgMsgTemp = "No Message";
                    final String strImgMsg = strImgMsgTemp;
                    if (checkIfClosed()) {
                        if (oldcodeon)
                            localNotification("", strImgMsg, 0);
                        continue;
                    }//from   w ww . j a  va2  s .  co m
                    if (MainActivity.adlib.get(strImgMsg) == null && !strImgMsg.equalsIgnoreCase("No Message"))
                        Log.d(TAG, "image url start download for key: " + strImgMsg + ", url = " + strImgUrl);
                    else {
                        Log.d(TAG, "Image exists, or no message, not downloading..., key: " + strImgMsg);
                        continue;
                    }

                    if (strImgMsg.equalsIgnoreCase("$28")) {
                        Log.d("Portal", "Image exists, loading from cache");
                        imgShow(BitmapFactory.decodeResource(getResources(), R.drawable.singtel), strImgMsg);
                        continue;
                    } else if (strImgMsg.equalsIgnoreCase("$4.50")) {
                        Log.d("Portal", "Heineken Image exists, loading from cache");
                        imgShow(BitmapFactory.decodeResource(getResources(), R.drawable.heineken), strImgMsg);
                        continue;
                    }

                    ShutterbugManager.getSharedImageManager(BleepActivity.currentBleepActivity)
                            .download(strImgUrl, new ShutterbugManagerListener() {
                                @Override
                                public void onImageSuccess(ShutterbugManager imageManager, Bitmap bitmap,
                                        String url) {
                                    Log.d(TAG, "image url end download " + strImgUrl);
                                    if (strImgUrl.equalsIgnoreCase(AdDialog.getCurrentAdUrl()))
                                        return;
                                    if (AdDialog.howManyAdDialogsShowing == 1) {
                                        AdDialog.closeOnlyAdDialog();
                                    }
                                    final Bitmap bitmap2 = bitmap;

                                    imgShow(bitmap, strImgMsg);

                                    if (oldcodeon) {
                                        BleepActivity.currentBleepActivity.runOnUiThread(new Runnable() {
                                            public void run() {
                                                if (BleepActivity.isBackground)
                                                    localNotification("", strImgMsg, 0);
                                                AdDialog.showAdsDialog(BleepActivity.currentBleepActivity,
                                                        bitmap2, strImgUrl, adAspect);
                                            }
                                        });
                                    }
                                }

                                @Override
                                public void onImageFailure(ShutterbugManager imageManager, String url) {
                                    thisBleepService.eraseTriggerLog(bleep);//to cancel trigger log when trigger is cancelled
                                }
                            });
                } else if (oldcodeon == false) {//don't run anything else
                } else if (msgType.equalsIgnoreCase("alert") && oldcodeon) {

                    // show alert message
                    if (checkIfClosed() || BleepActivity.isBackground) {
                        localNotification(objMsg.optString(APIKeyDefineCommand.MSG_TITLE),
                                objMsg.optString(APIKeyDefineCommand.MSG_CONTENT), 1);
                    } else {
                        showAlert(objMsg.optString(APIKeyDefineCommand.MSG_TITLE),
                                objMsg.optString(APIKeyDefineCommand.MSG_CONTENT));
                    }
                } else if (msgType.equalsIgnoreCase("launch")) {
                    String intentAction = objMsg.optString(APIKeyDefineCommand.MSG_APP_INTENT);
                    String intentUri = objMsg.optString(APIKeyDefineCommand.MSG_APP_URI);
                    String intentType = "";
                    String intentExtras = objMsg.optString(APIKeyDefineCommand.MSG_APP_EXTRAS);
                    String cfmMsg = objMsg.optString(APIKeyDefineCommand.MSG_APP_CFM);
                    String failMsg = objMsg.optString(APIKeyDefineCommand.MSG_APP_FAIL);
                    processTypeLaunch(intentAction, intentUri, intentType, intentExtras, cfmMsg, failMsg, 2);
                } else if (msgType.equalsIgnoreCase("url")) {
                    String intentAction = Intent.ACTION_VIEW;
                    String intentUri = objMsg.optString(APIKeyDefineCommand.MSG_MEDIA_URL);
                    String intentType = "";
                    String intentExtras = "";
                    String cfmMsg = objMsg.optString(APIKeyDefineCommand.MSG_APP_CFM);
                    String failMsg = objMsg.optString(APIKeyDefineCommand.MSG_APP_FAIL);
                    processTypeLaunch(intentAction, intentUri, intentType, intentExtras, cfmMsg, failMsg, 3);
                } else if (msgType.equalsIgnoreCase("webview")) {
                    String intentAction = Intent.ACTION_VIEW;
                    String intentUri = objMsg.optString(APIKeyDefineCommand.MSG_MEDIA_URL);
                    String intentType = "";
                    String intentExtras = "";
                    String cfmMsg = objMsg.optString(APIKeyDefineCommand.MSG_NOTIF);
                    if (cfmMsg.equalsIgnoreCase(""))
                        cfmMsg = "View webpage?";
                    String failMsg = "";
                    processTypeLaunch(intentAction, intentUri, intentType, intentExtras, cfmMsg, failMsg, 4);
                } else if (msgType.equalsIgnoreCase("video")) {
                    String strVidUrl = objMsg.optString(APIKeyDefineCommand.MSG_MEDIA_URL);
                    Intent vidIntent = new Intent(this, VideoActivity.class);
                    vidIntent.putExtra("url", strVidUrl);
                    String notifMsg = objMsg.optString(APIKeyDefineCommand.MSG_NOTIF);
                    if (notifMsg.equalsIgnoreCase(""))
                        notifMsg = "Play video?";
                    if (!checkIfClosed() && BleepActivity.isVideoActivityOpen) {
                        thisBleepService.eraseTriggerLog(bleep);//to cancel trigger log when trigger is cancelled
                    } else if (checkIfClosed() || BleepActivity.isBackground) {
                        vidIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        vidIntent.setAction(Intent.ACTION_MAIN);
                        vidIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                        localNotification("", notifMsg, vidIntent, "Video opening failed!", 5);
                    } else {
                        BleepActivity.currentBleepActivity.startActivity(vidIntent);
                    }
                } else if (msgType.equalsIgnoreCase("audio")) {
                    String url = objMsg.optString(APIKeyDefineCommand.MSG_MEDIA_URL);
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        mediaPlayer.setDataSource(url);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mp.start();
                        }
                    });
                    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            return false;
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //      } else if (actionName.equalsIgnoreCase(BLEepService.INTENT_BLEEP_EXIT) && intent.getExtras().containsKey(BLEepService.INTENT_MSG_NAME)) {
        //         HashMap<String, Object> beaconOutInfo = (HashMap<String, Object>)intent.getSerializableExtra(BLEepService.INTENT_MSG_NAME);   
        //         //Log.d("debug!","debug! this beacon just went out "+beaconOutInfo.get("uuid")+" "+beaconOutInfo.get("major")+" "+beaconOutInfo.get("minor")+" "+beaconOutInfo.get("tag")+" "+beaconOutInfo.get("beaconID"));
    } else if (actionName.equalsIgnoreCase(BLEepService.INTENT_BLEEP_STATE)
            && intent.getExtras().containsKey(BLEepService.INTENT_MSG_NAME)) {
        int beaconState = intent.getIntExtra(BLEepService.INTENT_MSG_NAME, 99);
    }

    return START_NOT_STICKY;
}

From source file:se.eliga.aves.songs.BirdSpeciesXenoCantoPlayerFragment.java

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

    setHasOptionsMenu(true);/*from www. j  ava 2  s  .c o m*/

    mediaPlayer = new MediaPlayer();
    mediaController = new MediaController(getActivity(), false);
    mediaController.setMediaPlayer(this);
    mediaController.setAnchorView(view);

    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            if (what == -38) {
                return true; //not pretty.. http://stackoverflow.com/questions/15205855/error-19-0-mediaplayer/15206308#15206308
            } else {
                return false;
            }
        }
    });

    mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            progressBar.setProgress(percent);
        }
    });
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            handler.post(new Runnable() {
                public void run() {
                    progressBar.setVisibility(ProgressBar.GONE);
                    if (mediaController != null) {
                        mediaController.show(0);
                    }
                    if (mediaPlayer != null) {
                        try {
                            mediaPlayer.start();
                        } catch (Exception e) {
                            Log.d(TAG, "Could not start mediaplayer", e);
                        }
                    }
                }
            });
        }
    });
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            if (audioAutoNext.isChecked()) {
                int count = getListAdapter().getCount();
                XenoCantoAudio nextAudio;
                if (currentPosition < (count - 1)) {
                    nextAudio = (XenoCantoAudio) getListAdapter().getItem(++currentPosition);
                } else {
                    nextAudio = (XenoCantoAudio) getListAdapter().getItem(0);
                }
                initiatePlay(nextAudio);
            }
        }
    });
    loadBird(getCurrentBird());
    return view;
}

From source file:org.dharmaseed.android.PlayTalkActivity.java

public void playTalkButtonClicked(View view) {
    Log.d(LOG_TAG, "button pressed");
    MediaPlayer mediaPlayer = talkPlayerFragment.getMediaPlayer();
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.pause();/*from   w  ww  .java 2 s.  co  m*/
        setPPButton("ic_media_play");
    } else if (talkPlayerFragment.getMediaPrepared()) {
        mediaPlayer.start();
        setPPButton("ic_media_pause");
    } else {
        try {
            if (talk.isDownloaded()) {
                Log.d(LOG_TAG, "Playing from " + talk.getPath());
                mediaPlayer.setDataSource(talk.getPath());
            } else {
                mediaPlayer.setDataSource(talk.getAudioUrl());
            }
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            Log.e(LOG_TAG, e.toString());
        }
    }
}

From source file:com.mattprecious.prioritysms.receiver.AlarmReceiver.java

private void doNotify(Context context, BaseProfile profile) {
    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    MediaPlayer mediaPlayer = new MediaPlayer();

    try {/*from w w w.j  a va  2 s .  c  o  m*/
        if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL || profile.isOverrideSilent()) {
            mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
            mediaPlayer.setAudioStreamType(
                    profile.isOverrideSilent() ? AudioManager.STREAM_ALARM : AudioManager.STREAM_NOTIFICATION);
            mediaPlayer.setDataSource(context, profile.getRingtone());
            mediaPlayer.prepare();
            mediaPlayer.start();

            if (profile.isVibrate()) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(VIBRATE_PATTERN, -1);
            }
        }
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "failed to play audio", e);
    } catch (IOException e) {
        Log.e(TAG, "failed to play audio", e);
    }
}

From source file:net.potterpcs.recipebook.TimerFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    startButton = (Button) getActivity().findViewById(R.id.timerstartbutton);
    stopButton = (Button) getActivity().findViewById(R.id.timerstopbutton);
    display = (TextView) getActivity().findViewById(R.id.timerdisplay);
    minutePicker = (NumberPicker) getActivity().findViewById(R.id.minutepicker);
    secondPicker = (NumberPicker) getActivity().findViewById(R.id.secondpicker);
    timermin = (EditText) getActivity().findViewById(R.id.timerdisplayminutes);
    timersec = (EditText) getActivity().findViewById(R.id.timerdisplayseconds);

    if (minutePicker != null) {
        minutePicker.setMinValue(0);/*w w  w .  j a  v  a2s . c  o  m*/
        minutePicker.setMaxValue(99);
        secondPicker.setMinValue(0);
        secondPicker.setMaxValue(59);
        secondPicker.setFormatter(new Formatter() {
            @Override
            public String format(int value) {
                return String.format("%02d", value);
            }
        });
        getActivity().findViewById(R.id.pickerlayout).setVisibility(View.VISIBLE);
        display.setVisibility(View.GONE);
    }

    startButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            int seconds;
            if (minutePicker != null) {
                seconds = minutePicker.getValue() * 60 + secondPicker.getValue();
            } else {
                int m = Integer.parseInt(timermin.getEditableText().toString());
                int s = Integer.parseInt(timersec.getEditableText().toString());
                seconds = m * 60 + s;
                timermin.setText(timermin.getText(), BufferType.NORMAL);
                timersec.setText(timersec.getText(), BufferType.NORMAL);
            }
            startButton.setEnabled(false);
            stopButton.setEnabled(true);

            if (minutePicker == null) {
                timermin.setEnabled(false);
                timersec.setEnabled(false);
            } else {
                minutePicker.setEnabled(false);
                secondPicker.setEnabled(false);
                getActivity().findViewById(R.id.pickerlayout).setVisibility(View.GONE);
                display.setVisibility(View.VISIBLE);
            }

            if (display != null) {
                display.setText(DateUtils.formatElapsedTime(seconds));
            }

            timer = new CountDownTimer(seconds * 1000, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    //                  Log.i(TAG, "tick " + millisUntilFinished);
                    if (display != null) {
                        display.setText(DateUtils.formatElapsedTime(millisUntilFinished / 1000));
                    } else {
                        int totalsec = (int) (millisUntilFinished / 1000);
                        int s = totalsec % 60;
                        int m = totalsec / 60;
                        timermin.setText(String.format("%02d", m));
                        timersec.setText(String.format("%02d", s));
                    }
                }

                @Override
                public void onFinish() {
                    // Play a sound and show a message when the timer ends
                    MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.ding);
                    mp.setOnCompletionListener(new OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mp.release();
                        }
                    });
                    mp.setVolume(1.0f, 1.0f);
                    Toast.makeText(getActivity(), "Done!", Toast.LENGTH_LONG).show();
                    mp.start();
                    clearToZero();
                }
            };

            timer.start();
        }
    });

    stopButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            timer.cancel();
            clearToZero();
        }
    });
}

From source file:fm.krui.kruifm.StreamService.java

/**
 * Prepares the player for streaming and plays the audio upon completion.
 *///  w w w .  j  av a 2  s  . co  m
private void prepareAudio() {
    try {
        Log.v(TAG, "Attempting to play stream from " + streamUrl);
        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {

                // When the stream is buffered, kill prompt and start playing automatically.
                mp.start();
                isPrepared = true;

                // Clear cached track information and start audio service.
                setCurrentTrackInfo("", "", "");
                updateNotification("", "", true);
                setUpdateTimer(true);

                // Since we're not buffering anymore, hide the status bar from the user
                broadcastMessage(BROADCAST_COMMAND_STATUS_HIDE);
                Log.i(TAG, "Stream playback started.");

            }
        });

        // Prepares stream without blocking UI Thread
        mp.prepareAsync();
        updateStreamStatus(getString(R.string.stream_status_buffering), true);

    } catch (IllegalStateException e) {
        Log.e(TAG, "Caught IllegalStateException when preparing: ");
        e.printStackTrace();
    }
}