Example usage for android.media MediaPlayer MediaPlayer

List of usage examples for android.media MediaPlayer MediaPlayer

Introduction

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

Prototype

public MediaPlayer() 

Source Link

Document

Default constructor.

Usage

From source file:com.PPRZonDroid.MainActivity.java

/**
 * Play warning sound if airspeed goes below the selected value
 *
 * @param context// ww w  .ja v a 2  s  .  co m
 * @throws IllegalArgumentException
 * @throws SecurityException
 * @throws IllegalStateException
 * @throws IOException
 */
public void play_sound(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);
    //Set volume max!!!
    audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM,
            audioManager.getStreamMaxVolume(audioManager.STREAM_SYSTEM), 0);

    if (audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM) != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    }
}

From source file:org.linphone.LinphoneService.java

private synchronized void startRinging() {
    try {/* w w  w.  j  ava 2 s.c o  m*/
        if (mAudioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER) && mVibrator != null) {
            long[] patern = { 0, 1000, 1000 };
            mVibrator.vibrate(patern, 1);
        }
        if (mRingerPlayer == null) {
            mRingerPlayer = new MediaPlayer();
            mRingerPlayer.setAudioStreamType(AudioManager.STREAM_RING);
            mRingerPlayer.setDataSource(getApplicationContext(),
                    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE));
            mRingerPlayer.prepare();
            mRingerPlayer.setLooping(true);
            mRingerPlayer.start();
        } else {
            Log.w(LinphoneService.TAG, "already ringing");
        }
    } catch (Exception e) {
        Log.e(LinphoneService.TAG, "cannot handle incoming call", e);
    }

}

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

private void streamPartToDisk(String fileName, String part, int offset, int totalLength, boolean endOfPage)
        throws TTSFailedException {

    LOG.debug("Request to stream text to file " + fileName + " with text " + part);

    if (part.trim().length() > 0 || endOfPage) {

        HashMap<String, String> params = new HashMap<String, String>();

        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, fileName);

        TTSPlaybackItem item = new TTSPlaybackItem(part, new MediaPlayer(), totalLength, offset, endOfPage,
                fileName);/*from   www.  jav  a 2 s.  c  o m*/
        ttsItemPrep.put(fileName, item);

        int result = textToSpeech.synthesizeToFile(part, params, fileName);
        if (result != TextToSpeech.SUCCESS) {
            String message = "synthesizeToFile failed with result " + result;
            LOG.error(message);
            showTTSFailed(message);
            throw new TTSFailedException();
        }
    } else {
        LOG.debug("Skipping part, since it's empty.");
    }
}

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) {/*from www .j av a 2  s .  c  om*/
        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.Beat.RingdroidEditActivity.java

private void loadFromFile() {
    mFile = new File(mFilename);
    mExtension = getExtensionFromFilename(mFilename);

    /* SongMetadataReader metadataReader = new SongMetadataReader(
    this, mFilename);/*from  w w  w . ja  v a2  s.co m*/
     mTitle = metadataReader.mTitle;
     mArtist = metadataReader.mArtist;
     mAlbum = metadataReader.mAlbum;
     mYear = metadataReader.mYear;
     mGenre = metadataReader.mGenre;*/

    String titleLabel = mTitle;
    if (mArtist != null && mArtist.length() > 0) {
        titleLabel += " - " + mArtist;
    }
    setTitle(titleLabel);

    mLoadingStartTime = System.currentTimeMillis();
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;
    mProgressDialog = new ProgressDialog(RingdroidEditActivity.this);
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        public boolean reportProgress(double fractionComplete) {
            long now = System.currentTimeMillis();
            if (now - mLoadingLastUpdateTime > 100) {
                mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete));
                mLoadingLastUpdateTime = now;
            }
            return mLoadingKeepGoing;
        }
    };

    // Create the MediaPlayer in a background thread
    mCanSeekAccurately = false;
    new Thread() {
        public void run() {
            mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE));
            System.out.println("Seek test done, creating media player.");
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
            }
            ;
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);

                if (mSoundFile == null) {
                    mProgressDialog.dismiss();
                    String name = mFile.getName().toLowerCase();
                    String[] components = name.split("\\.");
                    String err;
                    if (components.length < 2) {
                        err = getResources().getString(R.string.no_extension_error);
                    } else {
                        err = getResources().getString(R.string.bad_extension_error) + " "
                                + components[components.length - 1];
                    }
                    final String finalErr = err;
                    Runnable runnable = new Runnable() {
                        public void run() {
                            handleFatalError("UnsupportedExtension", finalErr, new Exception());
                        }
                    };
                    mHandler.post(runnable);
                    return;
                }
            } catch (final Exception e) {
                mProgressDialog.dismiss();
                e.printStackTrace();
                mInfo.setText(e.toString());

                Runnable runnable = new Runnable() {
                    public void run() {
                        handleFatalError("ReadError", getResources().getText(R.string.read_error), e);
                    }
                };
                mHandler.post(runnable);
                return;
            }
            mProgressDialog.dismiss();
            if (mLoadingKeepGoing) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        finishOpeningSoundFile();
                    }
                };
                mHandler.post(runnable);
            } else {
                RingdroidEditActivity.this.finish();
            }
        }
    }.start();
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

private void startRinging() {
    FileLog.d("starting ringing for call " + call.id);
    dispatchStateChanged(STATE_WAITING_INCOMING);
    //ringtone=RingtoneManager.getRingtone(this, Settings.System.DEFAULT_RINGTONE_URI);
    //ringtone.play();
    SharedPreferences prefs = getSharedPreferences("Notifications", MODE_PRIVATE);
    ringtonePlayer = new MediaPlayer();
    ringtonePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override//ww w  . jav  a 2s  .  c om
        public void onPrepared(MediaPlayer mediaPlayer) {
            ringtonePlayer.start();
        }
    });
    ringtonePlayer.setLooping(true);
    ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING);
    try {
        String notificationUri;
        if (prefs.getBoolean("custom_" + user.id, false))
            notificationUri = prefs.getString("ringtone_path_" + user.id,
                    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
        else
            notificationUri = prefs.getString("CallsRingtonePath",
                    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
        ringtonePlayer.setDataSource(this, Uri.parse(notificationUri));
        ringtonePlayer.prepareAsync();
    } catch (Exception e) {
        FileLog.e(e);
        if (ringtonePlayer != null) {
            ringtonePlayer.release();
            ringtonePlayer = null;
        }
    }
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    int vibrate;
    if (prefs.getBoolean("custom_" + user.id, false))
        vibrate = prefs.getInt("calls_vibrate_" + user.id, 0);
    else
        vibrate = prefs.getInt("vibrate_calls", 0);
    if ((vibrate != 2 && vibrate != 4
            && (am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE
                    || am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL))
            || (vibrate == 4 && am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE)) {
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        long duration = 700;
        if (vibrate == 1)
            duration /= 2;
        else if (vibrate == 3)
            duration *= 2;
        vibrator.vibrate(new long[] { 0, duration, 500 }, 0);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
            && !((KeyguardManager) getSystemService(KEYGUARD_SERVICE)).inKeyguardRestrictedInputMode()
            && NotificationManagerCompat.from(this).areNotificationsEnabled()) {
        showIncomingNotification();
        FileLog.d("Showing incoming call notification");
    } else {
        FileLog.d("Starting incall activity for incoming call");
        try {
            PendingIntent.getActivity(VoIPService.this, 12345,
                    new Intent(VoIPService.this, VoIPActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0)
                    .send();
        } catch (Exception x) {
            FileLog.e("Error starting incall activity", x);
        }
    }

}

From source file:com.example.mydemos.view.RingtonePickerActivity.java

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
    Log.e("lys", "onItemClick position ==" + position + "id" + id);
    if (id == -1) {
        if (mHasSilentItem) {

            if ((mHasDefaultItem && (position == 1)) || !mHasDefaultItem) {
                Log.e("lys", "onItemClick silentItemChecked == true");
                //toneCur.moveToPosition(position);
                mSelectedId = SILENT_ID;
                mSelectedUri = null;/*from w w w  .ja va  2  s .  c o m*/
                silentItemChecked = true;
                defaultItemChecked = false;
                stopMediaPlayer();
                listView.invalidateViews();
                return;
            } else if (mHasDefaultItem && (position == 0)) {
                Log.e("lys", "onItemClick defaultItemChecked == true");
                //toneCur.moveToPosition(position);
                mSelectedId = DEFAULT_ID;
                mSelectedUri = mUriForDefaultItem;
                defaultItemChecked = true;
                silentItemChecked = false;
            }
        } else {
            if (mHasDefaultItem) {
                Log.e("lys", "onItemClick defaultItemChecked == true");
                //toneCur.moveToPosition(position);
                mSelectedId = DEFAULT_ID;
                mSelectedUri = mUriForDefaultItem;
                defaultItemChecked = true;
                silentItemChecked = false;
            }
        }

    } else {
        if (mHasSilentItem) {
            silentItemChecked = false;
            position--;
        }

        if (mHasDefaultItem) {
            defaultItemChecked = false;
            position--;
        }
    }
    if (id != -1) {
        toneCur.moveToPosition(position);
        Log.e("lys", "onItemClick position == " + position + "id ==" + id);
        long newId = toneCur.getLong(toneCur.getColumnIndex(MediaStore.Audio.Media._ID));
        mSelectedId = newId;
        Log.e("lys", " onItemClick mSelectedId==" + mSelectedId);

        //wuqingliang modify begin20130307
        if (tabName == SYSTEM_TONE) {
            BaseUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
            Log.e("lys", "BaseUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;111111");
        } else {
            BaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            Log.e("lys", "BaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;1111111");
        }
        //wuqingliang modify end
        mSelectedUri = ContentUris.withAppendedId(BaseUri, newId);
    }
    listView.invalidateViews();
    audioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    stopMediaPlayer();
    mMediaPlayer = new MediaPlayer();
    try {
        if (toneType == ALARM_TYPE)
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        else
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
        mMediaPlayer.setDataSource(RingtonePickerActivity.this, mSelectedUri);
        mMediaPlayer.prepare();
        mMediaPlayer.start();

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

/**
 * Called after audio format service processes the url and gets a streaming media url from it (if it was a playlist or something)
 * @param url//from  w w  w .  ja v  a2  s.  c  o  m
 */
private void playUrl(String url) {
    if (LOCAL_LOGD)
        log("playUrl " + url, "d");
    if (!mCurrentPlayerState.equals(ServiceRadioPlayer.STATE_INITIALIZING)) {
        if (LOCAL_LOGV)
            log("incorrect state to play url", "v");
        return;
    }
    this.stopAndReleasePlayer(mMediaPlayer);
    this.mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mCurrentPlayerState = ServiceRadioPlayer.STATE_PREPARING;

    //get playlist data
    AsyncTaskPlaylist playlist = new AsyncTaskPlaylist();
    playlist.execute(mUrl);
    if (LOCAL_LOGV)
        log("get metadata", "v");
    if (!mMetadataRunnable.isRunning()) {
        mMetadataRunnable.init();
    }

    //play url
    try {
        //str += mUrl;
        if (LOCAL_LOGV)
            log("setting datasource for '" + mTitle + "' at '" + url + "'", "v");
        mMediaPlayer.setDataSource(url);
        initializePlayer(mMediaPlayer);

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        log("IllegalArgumentException, setting data source failed", "e");
        if (LOCAL_LOGV)
            e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        log("SecurityException, setting data source failed", "e");
        if (LOCAL_LOGV)
            e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        log("IllegalStateException, setting data source failed", "e");
        if (LOCAL_LOGV)
            e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //TODO handle this somehow, let user know
        log("IOException, setting data source failed", "e");
        if (LOCAL_LOGV)
            e.printStackTrace();
    }

    mMediaPlayer.prepareAsync(); // might take long! (for buffering, etc)
    if (LOCAL_LOGV)
        log("preparing async", "v");

}

From source file:github.daneren2005.dsub.service.DownloadServiceImpl.java

private synchronized void setupNext(final DownloadFile downloadFile) {
    try {/*from   w  w  w .j a v a 2 s.c o  m*/
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        if (nextMediaPlayer != null) {
            nextMediaPlayer.setOnCompletionListener(null);
            nextMediaPlayer.release();
            nextMediaPlayer = null;
        }
        nextMediaPlayer = new MediaPlayer();
        nextMediaPlayer.setWakeMode(DownloadServiceImpl.this, PowerManager.PARTIAL_WAKE_LOCK);
        try {
            nextMediaPlayer.setAudioSessionId(mediaPlayer.getAudioSessionId());
        } catch (Throwable e) {
            nextMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        nextMediaPlayer.setDataSource(file.getPath());
        setNextPlayerState(PREPARING);

        nextMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mp) {
                try {
                    setNextPlayerState(PREPARED);

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                            && (playerState == PlayerState.STARTED || playerState == PlayerState.PAUSED)) {
                        mediaPlayer.setNextMediaPlayer(nextMediaPlayer);
                        nextSetup = true;
                    }
                } catch (Exception x) {
                    handleErrorNext(x);
                }
            }
        });

        nextMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
                Log.w(TAG, "Error on playing next " + "(" + what + ", " + extra + "): " + downloadFile);
                return true;
            }
        });

        nextMediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleErrorNext(x);
    }
}

From source file:ac.robinson.paperchains.PaperChainsActivity.java

private void streamAudio(String audioPath) {
    resetAudioPlayer();/*  w ww. j a  va 2  s .  c o m*/

    mPlayButton.setVisibility(View.VISIBLE); // undo invisible by resetAudioPlayer();
    mPlayButton.setImageResource(R.drawable.ic_refresh_white_24dp);
    mPlayButton.startAnimation(mRotateAnimation);

    mAudioPlayer = new MediaPlayer();
    mAudioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
        try {
            // slightly hacky way of detecting whether the path is a url or a file, and handling appropriately
            new URL(audioPath); // only for the exception it throws
            mAudioPlayer.setDataSource(audioPath);
        } catch (MalformedURLException e) {
            FileInputStream inputStream = new FileInputStream(audioPath);
            mAudioPlayer.setDataSource(inputStream.getFD());
            inputStream.close();
        }
        mAudioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                mPlayButton.clearAnimation();
                mPlayButton.setImageResource(R.drawable.ic_pause_white_24dp);
            }
        });
        mAudioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mPlayButton.clearAnimation();
                mPlayButton.setImageResource(R.drawable.ic_play_arrow_white_24dp);
            }
        });
        mAudioPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                streamAudioLoadFailed(R.string.hint_soundcloud_load_failed);
                return true;
            }
        });
        mAudioPlayer.prepareAsync();
    } catch (IOException e) {
        streamAudioLoadFailed(R.string.hint_soundcloud_load_failed);
    }
}