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:github.daneren2005.dsub.service.DownloadService.java

@Override
public void onCreate() {
    super.onCreate();

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();//from  w ww.  j  a va 2s .  c om

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            audioSessionId = -1;
            Integer id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            if (id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();
                    prefs.edit().putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId).commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientHelper.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();
}

From source file:fm.smart.r1.activity.CreateSoundActivity.java

private static void playSound(FileDescriptor fileDescriptor) {

    if (mMediaPlayer != null) {
        mMediaPlayer.release();//from w w w  .  j a va 2 s . com
        mMediaPlayer = null;
    }

    mMediaPlayer = new MediaPlayer();

    try {
        mMediaPlayer.setDataSource(fileDescriptor);
    } catch (IllegalArgumentException 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();
    }
    try {
        mMediaPlayer.prepare();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mMediaPlayer.start();

    // if (action.equals(Intent.ACTION_PICK)
    // || action.equals(Intent.ACTION_GET_CONTENT)) {
    // Uri uri = ContentUris.withAppendedId(getIntent().getData(), list_id);
    //
    // Intent intent = getIntent();
    // intent.setData(uri);
    // setResult(RESULT_OK, intent);
    // } else {
    // Uri uri = ContentUris.withAppendedId(SmartFm.Items.CONTENT_URI,
    // list_id);
    //
    // startActivity(new Intent(Intent.ACTION_VIEW, uri));
    // }
}

From source file:com.somexapps.wyre.services.MediaService.java

private void playSong(int indexOfSongToPlay) {
    Song toPlay = null;//from   www .  ja  v  a 2 s  .c  om
    if (indexOfSongToPlay != -1) {
        // Save the index
        playingSongIndex = indexOfSongToPlay;

        toPlay = songsList.get(indexOfSongToPlay);
    }

    if (toPlay != null) {
        // Make sure song is not paused and song we're trying to play is a different one
        if (!isPaused || !toPlay.getData().equals(playingSong.getData())) {
            // Get URI for media
            // Save playing song uri for later reference
            playingSong = toPlay;

            // Reset the media player if not null, otherwise recreate it
            if (mediaPlayer != null) {
                mediaPlayer.reset();
            } else {
                mediaPlayer = new MediaPlayer();
            }

            // Try to prepare the media for playing
            try {
                // Set the data source from the grabbed URI
                mediaPlayer.setDataSource(playingSong.getData());

                // Prepare asynchronously, listener will get called after preparation
                mediaPlayer.setOnPreparedListener(this);
                mediaPlayer.prepareAsync();
            } catch (IOException e) {
                // TODO: Handle this error
                // Print it to logcat
                Log.e(TAG, e.getMessage());
            }
        } else {
            mediaPlayer.start();
            isPaused = false;
        }
    } else if (isPaused) {
        mediaPlayer.start();
        isPaused = false;
    }
}

From source file:com.intel.xdk.audio.Audio.java

public void startPlaying(String url) {
    if (mediaPlayer != null) {
        try {//from   w ww  .  j  av a  2s.  co m
            if (mediaPlayer.isPlaying()) {
                injectJS(
                        "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.audio.play.busy',true,true);document.dispatchEvent(ev);");
                return;
            }
        } catch (Exception e) {
        }
        mediaPlayer.release();
        mediaPlayer = null;
    }
    String path = fileFromUrl(url);
    File file = new File(path);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
    try {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnErrorListener(soundOnError);
        mediaPlayer.setOnCompletionListener(soundOnComplete);
        mediaPlayer.setDataSource(fis.getFD());
        mediaPlayer.prepare();
        mediaPlayer.start();
    } catch (Exception e) {
        injectJS(
                "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.audio.play.error',true,true);document.dispatchEvent(ev);");
        return;
    }
    injectJS(
            "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.audio.play.start',true,true);document.dispatchEvent(ev);");
}

From source file:com.kasungunathilaka.sarigama.service.PlayerService.java

public void previous() {
    try {/*  www  . j  ava  2s .  c  o m*/
        int position = playerQueue.getCurrentPosition();
        slavePlayer = new MediaPlayer();
        slavePlayer.setOnPreparedListener(this);
        slavePlayer.setOnErrorListener(this);
        slavePlayer.setOnCompletionListener(this);
        if (playerQueue.hasPosition((position - 1))) {
            localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_PREPARING));
            playerQueue.setCurrentPosition((position - 1));
            Song currentSong = playerQueue.getSongByPosition((position - 1));
            if (currentSong.getSongSource() == null) {
                getSongData(playerQueue.getCurrentPosition());
            } else {
                slavePlayer.setDataSource(currentSong.getSongSource());
                slavePlayer.prepareAsync();
            }
        } else {
            localBroadcastManager.sendBroadcast(new Intent(HomeActivity.ON_COMPLETED));
            this.seekTo(0);
            mainPlayer.stop();
            mainPlayer.release();
            mainPlayer = null;
            slavePlayer = null;
            playerQueue.setCurrentPosition(0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.karura.framework.plugins.Capture.java

/**
 * Get the Image specific attributes//from   w  w w  . j  a va2s .c o m
 * 
 * @param filePath
 *            path to the file
 * @param obj
 *            represents the Media File Data
 * @param video
 *            if true get video attributes as well
 * @return a JSONObject that represents the Media File Data
 * @throws JSONException
 */
private JSONObject getAudioVideoMetadata(String filePath, JSONObject obj, boolean video) throws JSONException {
    MediaPlayer player = new MediaPlayer();
    try {
        player.setDataSource(filePath);
        player.prepare();
        obj.put(DURATION_FIELD, player.getDuration());
        if (video) {
            obj.put(HEIGHT_FIELD, player.getVideoHeight());
            obj.put(WIDTH_FIELD, player.getVideoWidth());
        }
    } catch (IOException e) {
        Log.d(LOG_TAG, "Error: loading video file");
    }
    return obj;
}

From source file:com.example.android.supportv7.media.LocalPlayer.java

private void reset() {
    if (mMediaPlayer != null) {
        mMediaPlayer.stop();//  ww  w .j a  v a 2s . com
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnErrorListener(this);
    mMediaPlayer.setOnSeekCompleteListener(this);
    updateSurface();
    mState = STATE_IDLE;
    mSeekToPos = 0;
}

From source file:se.erichansander.retrotimer.TimerKlaxon.java

private void play(boolean ring, boolean vibrate) {
    TinyTracelog.trace("5");

    // stop() checks to see if we are already playing.
    stop();//from   ww w  .ja  v  a  2 s  . c om

    if (ring) {
        TinyTracelog.trace("5.1");
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnErrorListener(new OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                TinyTracelog.trace("5.1.e1");
                stop();
                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.
             */
            if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
                TinyTracelog.trace("5.1.1");
                mMediaPlayer.setVolume(IN_CALL_VOLUME, IN_CALL_VOLUME);
                setDataSourceFromResource(getResources(), mMediaPlayer, R.raw.in_call_alarm);
            } else {
                TinyTracelog.trace("5.1.2");
                setDataSourceFromResource(getResources(), mMediaPlayer, R.raw.classic_alarm);
            }
        } catch (Exception ex) {
            // Failed to set data source. Not much we can do to save
            // the situation though...
            TinyTracelog.trace("5.1.e2");
        }

        try {
            final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            // do not play alarms if stream volume is 0
            int volume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
            TinyTracelog.trace("5.1.3 " + volume);
            if (volume != 0) {
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mMediaPlayer.setLooping(true);
                mMediaPlayer.prepare();
                if (mAudioFocusHelper != null) {
                    mAudioFocusHelper.requestFocus();
                }
                mMediaPlayer.start();
            }
        } catch (Exception ex) {
            // Failed to play ring tone. Not much we can do to save
            // the situation though...
            TinyTracelog.trace("5.1.e3");
        }
    }

    /* Start the vibrator after everything is ok with the media player */
    if (vibrate) {
        TinyTracelog.trace("5.2");
        mVibrator.vibrate(sVibratePattern, 0);
    } else {
        mVibrator.cancel();
    }

    mPlaying = true;
}

From source file:org.catrobat.catroid.ui.controller.SoundController.java

private void handleSoundInfo(SoundViewHolder holder, SoundInfo soundInfo, SoundBaseAdapter soundAdapter,
        int position, Context context) {
    try {/* w  ww .  jav a  2s. co  m*/
        MediaPlayer tempPlayer = new MediaPlayer();
        tempPlayer.setDataSource(soundInfo.getAbsolutePath());
        tempPlayer.prepare();

        long milliseconds = tempPlayer.getDuration();
        long seconds = milliseconds / 1000;
        if (seconds == 0) {
            seconds = 1;
        }
        String timeDisplayed = DateUtils.formatElapsedTime(seconds);

        holder.timePlayedChronometer.setText(timeDisplayed);
        holder.timePlayedChronometer.setVisibility(Chronometer.VISIBLE);

        if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
            SoundBaseAdapter.setElapsedMilliSeconds(0);
        } else {
            SoundBaseAdapter.setElapsedMilliSeconds(
                    SystemClock.elapsedRealtime() - SoundBaseAdapter.getCurrentPlayingBase());
        }

        if (soundInfo.isPlaying) {
            holder.playAndStopButton.setImageResource(R.drawable.ic_media_stop);
            holder.playAndStopButton.setContentDescription(context.getString(R.string.sound_stop));

            if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
                startPlayingSound(holder.timePlayedChronometer, position, soundAdapter);
            } else if ((position == soundAdapter.getCurrentPlayingPosition())
                    && (SoundBaseAdapter.getElapsedMilliSeconds() > (milliseconds - 1000))) {
                stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
            } else {
                continuePlayingSound(holder.timePlayedChronometer, SystemClock.elapsedRealtime());
            }
        } else {
            holder.playAndStopButton.setImageResource(R.drawable.ic_media_play);
            holder.playAndStopButton.setContentDescription(context.getString(R.string.sound_play));
            stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
        }

        tempPlayer.reset();
        tempPlayer.release();
    } catch (IOException ioException) {
        Log.e(TAG, "Cannot get view.", ioException);
    }
}

From source file:com.google.fpl.gim.examplegame.MainService.java

@Override
public void onCreate() {
    // The service is being created.
    Utils.logDebug(TAG, "onCreate");
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_1);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_2);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_3);
    registerReceiver(mReceiver, intentFilter);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Determines the behavior for handling Audio Focus surrender.
    mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override//  ww w  .j  a v  a2s. c  om
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                    || focusChange == AudioManager.AUDIOFOCUS_LOSS) {

                if (mTextToSpeech.isSpeaking()) {
                    mTextToSpeech.setOnUtteranceProgressListener(null);
                    mTextToSpeech.stop();
                }

                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                }

                // Abandon Audio Focus, if it's requested elsewhere.
                mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);

                // Restart the current moment if AudioFocus was lost. Since AudioFocus is only
                // requested away from this application if this application was using it,
                // only Moments that play sound will restart in this way.
                if (mMission != null) {
                    mMission.restartMoment();
                }
            }
        }
    };

    // Asynchronously prepares the TextToSpeech.
    mTextToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                // Check if language is available.
                switch (mTextToSpeech.isLanguageAvailable(DEFAULT_TEXT_TO_SPEECH_LOCALE)) {
                case TextToSpeech.LANG_AVAILABLE:
                case TextToSpeech.LANG_COUNTRY_AVAILABLE:
                case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
                    Utils.logDebug(TAG, "TTS locale supported.");
                    mTextToSpeech.setLanguage(DEFAULT_TEXT_TO_SPEECH_LOCALE);
                    mIsTextToSpeechReady = true;
                    break;
                case TextToSpeech.LANG_MISSING_DATA:
                    Utils.logDebug(TAG, "TTS missing data, ask for install.");
                    Intent installIntent = new Intent();
                    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                    startActivity(installIntent);
                    break;
                default:
                    Utils.logDebug(TAG, "TTS local not supported.");
                    break;
                }
            }
        }
    });

    mMediaPlayer = new MediaPlayer();
}