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:ui.GalleryFileActivity.java

private void doPlay() {
    recordBtn.setText("?");
    if (!TextUtils.isEmpty(voicePath)) {
        try {//from w  ww.  j a  va2s  . c om
            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.adityarathi.muo.services.AudioPlaybackService.java

/**
 * Initializes the MediaPlayer objects for this service session.
 *//*from   ww  w .  j  a v  a  2s  . c o  m*/
private void initMediaPlayers() {

    /*
     * Release the MediaPlayer objects if they are still valid.
     */
    if (mMediaPlayer != null) {
        mMediaPlayer.release();
        mMediaPlayer = null;
    }

    if (mMediaPlayer2 != null) {
        getMediaPlayer2().release();
        mMediaPlayer2 = null;
    }

    mMediaPlayer = new MediaPlayer();
    mMediaPlayer2 = new MediaPlayer();
    setCurrentMediaPlayer(1);

    getMediaPlayer().reset();
    getMediaPlayer2().reset();

    //Loop the players if the repeat mode is set to repeat the current song.
    if (getRepeatMode() == Common.REPEAT_SONG) {
        getMediaPlayer().setLooping(true);
        getMediaPlayer2().setLooping(true);
    }

    try {
        mMediaPlayer.setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
        getMediaPlayer2().setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
    } catch (Exception e) {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer2 = new MediaPlayer();
        setCurrentMediaPlayer(1);
    }

    //Set the mediaPlayers' stream sources.
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    getMediaPlayer2().setAudioStreamType(AudioManager.STREAM_MUSIC);

}

From source file:org.thoughtcrime.SMP.notifications.MessageNotifier.java

private static void sendInThreadNotification(Context context, Recipients recipients) {
    try {/*w w w . ja va2 s.  c om*/
        if (!TextSecurePreferences.isInThreadNotifications(context)) {
            return;
        }

        Uri uri = recipients.getRingtone();

        if (uri == null) {
            String ringtone = TextSecurePreferences.getNotificationRingtone(context);

            if (ringtone == null) {
                Log.w(TAG, "ringtone preference was null.");
                return;
            } else {
                uri = Uri.parse(ringtone);
            }
        }

        if (uri == null) {
            Log.w(TAG, "couldn't parse ringtone uri " + TextSecurePreferences.getNotificationRingtone(context));
            return;
        }

        MediaPlayer player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
        player.setDataSource(context, uri);
        player.setLooping(false);
        player.setVolume(0.25f, 0.25f);
        player.prepare();

        final AudioManager audioManager = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE));

        audioManager.requestAudioFocus(null, AudioManager.STREAM_NOTIFICATION,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                audioManager.abandonAudioFocus(null);
            }
        });

        player.start();
    } catch (IOException ioe) {
        Log.w("MessageNotifier", ioe);
    }
}

From source file:metrocasas.projectsgt.MainActivity.java

public void detenerGrabacion(View v) {
    myAudioRecorder.stop();//from www.  j a  v  a  2  s  .  c o  m
    myAudioRecorder.release();
    player = new MediaPlayer();
    player.setOnCompletionListener(this);
    audioNameFile.setText("ARCHIVO: " + audioFile.getName());
    try {
        player.setDataSource(audioFile.getAbsolutePath());
    } catch (IOException e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }
    try {
        player.prepare();
    } catch (IOException e) {
        Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
    }
    grabar.setEnabled(true);
    detener.setEnabled(false);
    escuchar.setEnabled(true);
}

From source file:com.owncloud.android.media.MediaService.java

/**
 * Makes sure the media player exists and has been reset. This will create the media player
 * if needed. reset the existing media player if one already exists.
 *///from  www. ja v a  2 s .com
protected void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();

        // make sure the CPU won't go to sleep while media is playing
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // the media player will notify the service when it's ready preparing, and when it's done playing
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);

    } else {
        mPlayer.reset();
    }
}

From source file:brama.com.hearthum.waveform.WaveformFragment.java

protected void loadFromFile() {
    mFile = new File(mFilename);
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;/*from w  w  w.  j a  v  a2s  .  c  om*/
    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener((DialogInterface dialog) -> mLoadingKeepGoing = false);
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = (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
    new Thread() {
        public void run() {
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Log.e(TAG, "Error while creating media player", e);
            }
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);
            } catch (final Exception e) {
                Log.e(TAG, "Error while loading sound file", e);
                mProgressDialog.dismiss();
                mInfo.setText(e.toString());
                return;
            }
            if (mLoadingKeepGoing) {
                mHandler.post(() -> finishOpeningSoundFile());
            }
        }
    }.start();
}

From source file:info.guardianproject.otr.app.im.app.MessageView.java

/**
 * @param mimeType/*from  ww w .  j a v  a 2  s .co  m*/
 * @param body
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void onClickMediaIcon(String mimeType, Uri mediaUri) {

    if (ChatFileStore.isVfsUri(mediaUri)) {
        if (mimeType.startsWith("image")) {
            Intent intent = new Intent(context, ImageViewActivity.class);
            intent.putExtra(ImageViewActivity.FILENAME, mediaUri.getPath());
            context.startActivity(intent);
            return;
        }
        if (mimeType.startsWith("audio")) {
            new AudioPlayer(getContext(), mediaUri.getPath(), mimeType).play();
            return;
        }
        return;
    } else {

        String body = convertMediaUriToPath(mediaUri);

        if (body == null)
            body = new File(mediaUri.getPath()).getAbsolutePath();

        if (mimeType.startsWith("audio")
                || (body.endsWith("3gp") || body.endsWith("3gpp") || body.endsWith("amr"))) {

            if (mMediaPlayer != null)
                mMediaPlayer.release();

            try {
                mMediaPlayer = new MediaPlayer();
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMediaPlayer.setDataSource(body);
                mMediaPlayer.prepare();
                mMediaPlayer.start();

                return;
            } catch (IOException e) {
                Log.e(ImApp.LOG_TAG, "error playing audio: " + body, e);
            }

        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 11)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

        //set a general mime type not specific
        intent.setDataAndType(Uri.parse(body), mimeType);

        Context context = getContext().getApplicationContext();

        if (isIntentAvailable(context, intent)) {
            context.startActivity(intent);
        } else {
            Toast.makeText(getContext(), R.string.there_is_no_viewer_available_for_this_file_format,
                    Toast.LENGTH_LONG).show();
        }
    }
}

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

/**
 * Prepares the player for the given playback request. If the holder is null
 * it is assumed this is an audio only source. If playOnReady is set to true
 * the media will begin playing as soon as it can.
 *
 * @see RequestUtils for the set of valid keys.
 *///from w w w .  j a  va2 s . c  om
public void setContent(Bundle request, SurfaceHolder holder) {
    String source = request.getString(RequestUtils.EXTRA_KEY_SOURCE);
    Map<String, String> headers = null; // request.mHeaders;
    boolean playOnReady = true; // request.mPlayOnReady;
    if (DEBUG) {
        Log.d(TAG, mDebugId + ": Settings new content. Have a player? " + (mPlayer != null)
                + " have a next player? " + (mNextPlayer != null));
    }
    cleanUpPlayer();
    setState(STATE_PREPARING);
    mPlayOnReady = playOnReady;
    mSeekOnReady = -1;
    final MediaPlayer newPlayer = new MediaPlayer();

    requestAudioFocus();

    mPlayer = newPlayer;
    mContent = new PlayerContent(source, headers);
    try {
        if (headers != null) {
            Uri sourceUri = Uri.parse(source);
            newPlayer.setDataSource(mContext, sourceUri, headers);
        } else {
            newPlayer.setDataSource(source);
        }
    } catch (Exception e) {
        setError(Listener.ERROR_LOAD_FAILED, 0, null, e);
        return;
    }
    if (isHolderReady(holder, newPlayer)) {
        preparePlayer(newPlayer, true);
    }
}

From source file:com.soubw.other.WaveformFragment.java

protected void loadFromFile() {
    mFile = new File(mFilename);
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;//from   w  ww . ja  v  a 2s .com
    mProgressDialog = new ProgressDialog(getActivity());
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setTitle(R.string.progress_dialog_loading);
    mProgressDialog.setCancelable(true);
    mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            mLoadingKeepGoing = false;
        }
    });
    mProgressDialog.show();

    final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() {
        @Override
        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
    new Thread() {
        public void run() {
            try {
                MediaPlayer player = new MediaPlayer();
                player.setDataSource(mFile.getAbsolutePath());
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.prepare();
                mPlayer = player;
            } catch (final java.io.IOException e) {
                Log.e(TAG, "Error while creating media player", e);
            }
        }
    }.start();

    // Load the sound file in a background thread
    new Thread() {
        public void run() {
            try {
                mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener);
            } catch (final Exception e) {
                Log.e(TAG, "Error while loading sound file", e);
                mProgressDialog.dismiss();
                mInfo.setText(e.toString());
                return;
            }
            if (mLoadingKeepGoing) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        finishOpeningSoundFile();
                    }
                });
            }
        }
    }.start();
}

From source file:com.allthatseries.RNAudioPlayer.Playback.java

/**
 * Makes sure the media player exists and has been reset. This will create
 * the media player if needed, or reset the existing media player if one
 * already exists.//  ww  w. ja v  a  2  s  . com
 */
private void createMediaPlayerIfNeeded() {
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();

        // Make sure the media player will acquire a wake-lock while
        // playing. If we don't do that, the CPU might go to sleep while the
        // song is playing, causing playback to stop.
        mMediaPlayer.setWakeMode(mContext.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // we want the media player to notify us when it's ready preparing,
        // and when it's done playing:
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnSeekCompleteListener(this);

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mMediaPlayer != null) {
                    try {
                        Thread.sleep(500);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                                    Intent intent = new Intent("update-position-event");
                                    intent.putExtra("currentPosition", mMediaPlayer.getCurrentPosition());
                                    LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
                                }
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    } else {
        mMediaPlayer.reset();
    }
}