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:at.wada811.app.fragment.VideoFragment.java

private void initMediaPlayer() {
    LogUtils.i();/* www .j  a  v a 2 s . com*/
    if (getArguments().keySet().contains(KEY_RES_ID)) {
        mMediaPlayer = MediaPlayer.create(getActivity(), getArguments().getInt(KEY_RES_ID));
    } else {
        mMediaPlayer = new MediaPlayer();
    }
    mMediaPlayer.setOnVideoSizeChangedListener(this);
    mMediaPlayer.setOnBufferingUpdateListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setOnInfoListener(new OnInfoListener() {
        @Override
        public boolean onInfo(MediaPlayer mp, int what, int extra) {
            switch (what) {
            case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                LogUtils.i("MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING");
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                LogUtils.i("MediaPlayer.MEDIA_INFO_BUFFERING_END");
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                LogUtils.i("MediaPlayer.MEDIA_INFO_BUFFERING_START");
                break;
            case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:
                LogUtils.i("MediaPlayer.MEDIA_INFO_METADATA_UPDATE");
                break;
            case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
                LogUtils.i("MediaPlayer.MEDIA_INFO_NOT_SEEKABLE");
                break;
            case MediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT:
                LogUtils.i("MediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT");
                break;
            case MediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE:
                LogUtils.i("MediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE");
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                LogUtils.i("MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START");
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
                LogUtils.i("MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING");
                break;
            case MediaPlayer.MEDIA_INFO_UNKNOWN:
            default:
                LogUtils.i("MediaPlayer.MEDIA_INFO_UNKNOWN");
                break;
            }
            LogUtils.d("extra: " + extra);
            return false;
        }
    });
    mMediaPlayer.setOnErrorListener(new OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            switch (what) {
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_SERVER_DIED");
                break;
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
            default:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_UNKNOWN");
                break;
            }
            switch (extra) {
            case MediaPlayer.MEDIA_ERROR_IO:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_IO");
                break;
            case MediaPlayer.MEDIA_ERROR_MALFORMED:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_MALFORMED");
                break;
            case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK");
                break;
            case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_TIMED_OUT");
                break;
            case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                LogUtils.e("MediaPlayer.MEDIA_ERROR_UNSUPPORTED");
                break;
            default:
                LogUtils.e("extra: " + extra);
                break;
            }
            return false;
        }
    });
    mCallback.onActivityCreated(this);
}

From source file:fr.bde_eseo.eseomega.GantierActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    view = new GPGameSurfaceView(this);
    setContentView(view);//from   w  w w  . ja v  a  2s . co  m

    gyroOrientation[0] = 0.0f;
    gyroOrientation[1] = 0.0f;
    gyroOrientation[2] = 0.0f;

    // initialise gyroMatrix with identity matrix
    gyroMatrix[0] = 1.0f;
    gyroMatrix[1] = 0.0f;
    gyroMatrix[2] = 0.0f;
    gyroMatrix[3] = 0.0f;
    gyroMatrix[4] = 1.0f;
    gyroMatrix[5] = 0.0f;
    gyroMatrix[6] = 0.0f;
    gyroMatrix[7] = 0.0f;
    gyroMatrix[8] = 1.0f;

    senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    profile = new UserProfile();
    profile.readProfilePromPrefs(this);

    // Create media player only if not playing
    if (mediaPlayer == null)
        mediaPlayer = new MediaPlayer();
}

From source file:com.shahenlibrary.VideoPlayer.VideoPlayerView.java

private void initPlayerIfNeeded() {
    if (mMediaPlayer != null) {
        return;//from  ww  w . ja v a 2  s .c  o m
    }
    Log.d(LOG_TAG, "initPlayerIfNeeded");
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setScreenOnWhilePlaying(true);
    mMediaPlayer.setOnVideoSizeChangedListener(this);
    mMediaPlayer.setOnErrorListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnBufferingUpdateListener(this);
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnInfoListener(this);
}

From source file:com.baruckis.nanodegree.spotifystreamer.PlayerService.java

@Override
public void onCreate() {
    //create the service
    super.onCreate();
    //create mMediaPlayer
    mMediaPlayer = new MediaPlayer();

    //initialize/*from w  ww .ja va 2 s .c  o  m*/
    trackPosition = 0;
    initMediaPlayer();
    initMediaSession();

    //Notification visibility (show controls on the lock screen or not)
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mShowNotification = prefs.getBoolean(getString(R.string.switch_preference_notification_key),
            getResources().getBoolean(R.bool.default_show_notification));

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(RECEIVE_BROADCAST_INTENT_PAUSE);
    intentFilter.addAction(RECEIVE_BROADCAST_INTENT_NOTIFICATION);
    LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, intentFilter);
}

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

private void play() {
    // stop() checks to see if we are already playing.
    stop();//from  www. j  a v a2 s  . c om

    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:org.awesomeapp.messenger.ui.GalleryListItem.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void onClickMediaIcon(String mimeType, Uri mediaUri) {

    if (SecureMediaStore.isVfsUri(mediaUri)) {
        if (mimeType.startsWith("image")) {
            Intent intent = new Intent(context, ImageViewActivity.class);
            intent.putExtra(ImageViewActivity.URI, mediaUri.toString());
            intent.putExtra(ImageViewActivity.MIMETYPE, mimeType);

            context.startActivity(intent);
            return;
        }/* w w w.j  a  v a2s  .co m*/
        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:ru.kudzmi.rajitaku.radioService.RadioService.java

private void initMediaPlayer() {
    mPlayer = new MediaPlayer();
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mPlayer.setOnPreparedListener(this);
    mPlayer.setOnErrorListener(this);
    mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
}

From source file:uk.co.gidley.clockRadio.RadioPlayerService.java

public void play(final String playerUri) {
    new Thread(new Runnable() {
        public void run() {
            setState(State.LOADING);

            if (StringUtils.isEmpty(playerUri)) {
                setState(State.STOPPED);
                return;
            }/*from www  . j a v  a2  s  . c  om*/

            if (mp != null && mp.isPlaying()) {
                stop();
            }

            // The uri could be a playlist file OR an actual stream check based on
            // file extension (TODO review if better way of doing this)
            String audioUri;
            if (playerUri.endsWith(".pls")) {
                audioUri = parsePls(playerUri);
            } else {
                audioUri = playerUri;
            }

            if (StringUtils.isEmpty(audioUri)) {
                setState(State.STOPPED);
                return;
            }
            Log.d(TAG, "Audio URL:" + audioUri);

            mp = new MediaPlayer();
            try {
                mp.setDataSource(audioUri);
                mp.prepare();
                mp.start();
                setState(State.PLAYING);
                showNotification();
            } catch (IllegalArgumentException e) {
                setState(State.STOPPED);
                Log.e(TAG, "Unable to open stream", e);
            } catch (IllegalStateException e) {
                setState(State.STOPPED);
                Log.e(TAG, "Unable to open stream", e);
            } catch (IOException e) {
                setState(State.STOPPED);
                Log.e(TAG, "Unable to open stream", e);
            }

            wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
            wl.acquire();
        }
    }).start();

}

From source file:com.todoroo.astrid.files.FilesControlSet.java

private static void play(String file, PlaybackExceptionHandler handler) {
    MediaPlayer mediaPlayer = new MediaPlayer();

    try {/* w  ww  . j  a v a  2 s . c o  m*/
        mediaPlayer.setDataSource(file);
        mediaPlayer.prepare();
        mediaPlayer.start();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        handler.playbackFailed();
    }
}

From source file:com.adkdevelopment.simpleflashlightadfree.ui.EmergencyFragment.java

/**
 * Starts emergency sound from assets/*from ww w  . jav  a2 s . c o  m*/
 */
public void emergencySignal() {

    try {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying() && status == FlashlightService.STATUS_OFF) {
            mMediaPlayer.stop();
            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;

            mLinearLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorBackground));
        } else if (status == FlashlightService.STATUS_BLINK) {

            final AnimationDrawable drawable = new AnimationDrawable();
            final Handler handler = new Handler();

            drawable.addFrame(new ColorDrawable(Color.RED), 400);
            drawable.addFrame(new ColorDrawable(Color.BLUE), 400);
            drawable.setOneShot(false);

            mLinearLayout.setBackground(drawable);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    drawable.start();
                }
            }, 100);

            mMediaPlayer = new MediaPlayer();
            AssetFileDescriptor descriptor = getActivity().getAssets().openFd("sews.mp3");
            mMediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(),
                    descriptor.getLength());
            descriptor.close();

            mMediaPlayer.prepare();
            mMediaPlayer.setVolume(1f, 1f);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}