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:org.moire.ultrasonic.service.DownloadServiceImpl.java

@SuppressLint("NewApi")
@Override/*from  ww  w  .j  av  a2 s .c o  m*/
public void onCreate() {
    super.onCreate();

    new Thread(new Runnable() {
        @Override
        public void run() {
            Thread.currentThread().setName("DownloadServiceImpl");

            Looper.prepare();

            if (mediaPlayer != null) {
                mediaPlayer.release();
            }

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

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

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

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).start();

    audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    setUpRemoteControlClient();

    if (equalizerAvailable) {
        equalizerController = new EqualizerController(this, mediaPlayer);
        if (!equalizerController.isAvailable()) {
            equalizerController = null;
        } else {
            equalizerController.loadSettings();
        }
    }
    if (visualizerAvailable) {
        visualizerController = new VisualizerController(mediaPlayer);
        if (!visualizerController.isAvailable()) {
            visualizerController = null;
        }
    }

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

    instance = this;
    lifecycleSupport.onCreate();
}

From source file:de.tubs.ibr.dtn.dtalkie.service.TalkieService.java

@Override
public void onCreate() {
    // call onCreate of the super-class
    super.onCreate();

    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // get the audio-manager
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(mPrefListener);

    // create message database
    mDatabase = new MessageDatabase(this);

    // init sound pool
    mSoundManager = new SoundFXManager(AudioManager.STREAM_VOICE_CALL, 2);

    mSoundManager.load(this, Sound.BEEP);
    mSoundManager.load(this, Sound.CONFIRM);
    mSoundManager.load(this, Sound.QUIT);
    mSoundManager.load(this, Sound.RING);
    mSoundManager.load(this, Sound.SQUELSH_LONG);
    mSoundManager.load(this, Sound.SQUELSH_SHORT);

    // create a player
    mPlayer = new MediaPlayer();
    mPlayer.setOnCompletionListener(mCompletionListener);
    mPlayer.setOnPreparedListener(mPrepareListener);

    // create registration
    Registration reg = new Registration("dtalkie");
    reg.add(RecorderService.TALKIE_GROUP_EID);

    // register own data handler for incoming bundles
    mClient = new DTNClient(_session_listener);

    try {//  ww  w .jav  a  2  s  . c om
        mClient.initialize(this, reg);
        mServiceError = ServiceError.NO_ERROR;
    } catch (ServiceNotAvailableException e) {
        mServiceError = ServiceError.SERVICE_NOT_FOUND;
    } catch (SecurityException ex) {
        mServiceError = ServiceError.PERMISSION_NOT_GRANTED;
    }

    Log.d(TAG, "Service created.");

    if (prefs.getBoolean("autoplay", false) || HeadsetService.ENABLED) {
        Intent play_i = new Intent(TalkieService.this, TalkieService.class);
        play_i.setAction(TalkieService.ACTION_PLAY_NEXT);
        startService(play_i);
    }
}

From source file:com.quran.labs.androidquran.service.AudioService.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.// w w  w.j  ava2  s  .  c o m
 */
private void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = 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.
        //
        // Remember that to use this, we have to declare the
        // android.permission.WAKE_LOCK permission in AndroidManifest.xml.
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

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

From source file:CookieVideoView.java

private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
        // not ready for playback just yet, will try again later
        return;/*from   w  w  w .  j a  v  a  2s  .c om*/
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    mContext.sendBroadcast(i);

    // we shouldn't clear the target state, because somebody might have
    // called start() previously
    release(false);
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnInfoListener(mOnInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mCurrentBufferPercentage = 0;
        mMediaPlayer.setDataSource(mContext, mUri, mHeaders);
        mMediaPlayer.setDisplay(mSurfaceHolder);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);
        mMediaPlayer.prepareAsync();
        // we don't set the target state here either, but preserve the
        // target state that was there before.
        mCurrentState = STATE_PREPARING;
        attachMediaController();
    } catch (IOException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
        return;
    } catch (IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
        return;
    }
}

From source file:com.snappy.VoiceActivity.java

private void startPlaying() {
    if (mIsPlaying == 0) {
        mPlayer = new MediaPlayer();
        try {// w  w w  .j av  a  2 s  .  c om
            mPlayer.setDataSource(sFileName);
            mPlayer.prepare();
            mPlayer.start();
            mPbForPlaying.setMax((int) mPlayer.getDuration());

            mRunnForProgressBar = new Runnable() {

                @Override
                public void run() {
                    mPbForPlaying.setProgress((int) mPlayer.getCurrentPosition());
                    if (mPlayer.getDuration() - 99 > mPlayer.getCurrentPosition()) {
                        mHandlerForProgressBar.postDelayed(mRunnForProgressBar, 100);
                    } else {
                        mPbForPlaying.setProgress((int) mPlayer.getDuration());
                    }
                }
            };
            mHandlerForProgressBar.post(mRunnForProgressBar);
            mIsPlaying = 2;
            return;
        } catch (IOException e) {
            Log.e("LOG", "prepare() failed");
        }
    } else if (mIsPlaying == 1) {
        mPlayer.start();
        mHandlerForProgressBar.post(mRunnForProgressBar);
        mIsPlaying = 2;
    }
}

From source file:com.securecomcode.text.notifications.MessageNotifier.java

private static void sendInThreadNotification(Context context) {
    try {/* ww  w  .  ja  v a 2  s. c o  m*/
        if (!TextSecurePreferences.isInThreadNotifications(context)) {
            return;
        }

        String ringtone = TextSecurePreferences.getNotificationRingtone(context);

        if (ringtone == null)
            return;

        Uri uri = Uri.parse(ringtone);
        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:android.widget.TiVideoView4.java

private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
        // not ready for playback just yet, will try again later
        return;//from  ww w. j a v  a2s  . c  o m
    }
    // Tell the music playback service to pause
    // TODO: these constants need to be published somewhere in the framework.
    Intent i = new Intent("com.android.music.musicservicecommand");
    i.putExtra("command", "pause");
    getContext().sendBroadcast(i);

    if (mMediaPlayer != null) {
        mMediaPlayer.reset();
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mIsPrepared = false;
        Log.v(TAG, "reset duration to -1 in openVideo");
        mDuration = -1;
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mCurrentBufferPercentage = 0;
        if (URLUtil.isAssetUrl(mUri.toString())) { // DST: 20090606 detect asset url
            AssetFileDescriptor afd = null;
            try {
                String path = mUri.toString().substring("file:///android_asset/".length());
                afd = getContext().getAssets().openFd(path);
                mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            } finally {
                if (afd != null) {
                    afd.close();
                }
            }
        } else {
            setDataSource();
        }
        mMediaPlayer.setDisplay(mSurfaceHolder);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);
        mMediaPlayer.prepareAsync();
        attachMediaController();
    } catch (IOException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        return;
    } catch (IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        return;
    }
}

From source file:com.lithiumli.fiction.PlaybackService.java

private void prepareNext() {
    int position = mQueue.getCurrentPosition();

    if (position >= mQueue.getCount() - 1) {
        // TODO: repeat modes
        return;/*from  w  w w .  ja va 2s.c om*/
    }

    Song song = mQueue.getItem(position + 1);
    try {
        mNextPlayer = new MediaPlayer();
        mNextPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mNextPlayer.setDataSource(getApplicationContext(), song.getUri());
        mNextPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer player) {
                if (mMediaPlayer == null) {
                } else {
                    mMediaPlayer.setNextMediaPlayer(player);
                    mMediaPlayer.setOnCompletionListener(PlaybackService.this);
                    player.setOnCompletionListener(PlaybackService.this);
                }
            }
        });
        mNextPlayer.prepareAsync();
    } catch (IOException e) {
    }
}

From source file:com.brayanarias.alarmproject.activity.AlarmScreenActivity.java

private void playRingtone(String tone) {
    mediaPlayer = new MediaPlayer();
    try {//www . j av a 2  s  .  c  om
        Uri ringtoneUri;
        if (tone.equals("default")) {
            ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        } else {
            ringtoneUri = Uri.parse(tone);
        }

        if (ringtoneUri != null) {
            mediaPlayer.setDataSource(this, ringtoneUri);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mediaPlayer.setLooping(true);
            mediaPlayer.prepare();
            AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            actualVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
            incrementVolume();
            mediaPlayer.start();
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, 1, 0);
        }
    } catch (Exception e) {
        Log.e(tag, e.getLocalizedMessage(), e);
    }
}

From source file:com.mishiranu.dashchan.content.service.AudioPlayerService.java

private void initAndPlayAudio(File file) {
    audioFile = file;/*from  w w w . ja  v a 2 s  . c om*/
    pausedByTransientLossOfFocus = false;
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setLooping(false);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    try {
        mediaPlayer.setDataSource(file.getPath());
        mediaPlayer.prepare();
    } catch (Exception e) {
        audioFile.delete();
        CacheManager.getInstance().handleDownloadedFile(audioFile, false);
        ToastUtils.show(context, R.string.message_playback_error);
        cleanup();
        stopSelf();
        sendToActivity(ACTION_CANCEL);
        return;
    }
    play(true);
    refreshPlaybackNotification(true);
}