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:be.ugent.zeus.hydra.util.audiostream.MusicService.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.
 *///from w w w .jav  a2s. c  om
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);
    } else {
        mPlayer.reset();
    }
}

From source file:org.apache.cordova.Capture.java

/**
 * Get the Image specific attributes//from   w  ww.  j a v  a2  s. 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 getAudioVideoData(String filePath, JSONObject obj, boolean video) throws JSONException {
    MediaPlayer player = new MediaPlayer();
    try {
        player.setDataSource(filePath);
        player.prepare();
        obj.put("duration", player.getDuration() / 1000);
        if (video) {
            obj.put("height", player.getVideoHeight());
            obj.put("width", player.getVideoWidth());
        }
    } catch (IOException e) {
        Log.d(LOG_TAG, "Error: loading video file");
    }
    return obj;
}

From source file:leoisasmendi.android.com.suricatepodcast.services.MediaPlayerService.java

private void initMediaPlayer() {
    mediaPlayer = new MediaPlayer();
    //Set up MediaPlayer event listeners
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnBufferingUpdateListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnInfoListener(this);
    //Reset so that the MediaPlayer is not pointing to another data source
    mediaPlayer.reset();/*from w w  w.  jav  a  2s .  c o m*/

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        publishStatus(STATUS_FETCHING);
        // Set the data source to the mediaFile location
        mediaPlayer.setDataSource(activeAudio.getAudio());
        mediaPlayer.prepareAsync();
    } catch (Exception e) {
        e.printStackTrace();
        publishStatus(STATUS_ERROR);
        stopSelf();
        Log.d(TAG, "initMediaPlayer: " + R.string.media_player_error_1);
    }
}

From source file:com.wsi.audiodemo.ScrollingActivity.java

private void playSound3(String assetName) {
    try {/* w w  w.ja v a 2s.c  o m*/
        AssetFileDescriptor afd = getAssets().openFd("sounds/" + assetName + ".mp3");
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    } catch (Exception ex) {
        Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:com.smithdtyler.prettygoodmusicplayer.MusicPlaybackService.java

@Override
public synchronized void onCreate() {
    Log.i(TAG, "Music Playback Service Created!");
    isRunning = true;/*w  w w .  java  2  s. co  m*/
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PGMPWakeLock");

    random = new Random();

    mp = new MediaPlayer();
    mReadaheadThread = new ReadaheadThread();

    mp.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            Log.i(TAG, "Song complete");
            next();
        }

    });

    // https://developer.android.com/training/managing-audio/audio-focus.html
    audioFocusListener = new PrettyGoodAudioFocusChangeListener();

    // Get permission to play audio
    am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

    HandlerThread thread = new HandlerThread("ServiceStartArguments");
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);

    // https://stackoverflow.com/questions/19474116/the-constructor-notification-is-deprecated
    // https://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly/15538209#15538209
    Intent resultIntent = new Intent(this, NowPlaying.class);
    resultIntent.putExtra("From_Notification", true);
    resultIntent.putExtra(AlbumList.ALBUM_NAME, album);
    resultIntent.putExtra(ArtistList.ARTIST_NAME, artist);
    resultIntent.putExtra(ArtistList.ARTIST_ABS_PATH_NAME, artistAbsPath);

    // Use the FLAG_ACTIVITY_CLEAR_TOP to prevent launching a second
    // NowPlaying if one already exists.
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

    Builder builder = new NotificationCompat.Builder(this.getApplicationContext());

    String contentText = getResources().getString(R.string.ticker_text);
    if (songFile != null) {
        contentText = Utils.getPrettySongName(songFile);
    }

    Notification notification = builder.setContentText(contentText).setSmallIcon(R.drawable.ic_pgmp_launcher)
            .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent)
            .setContentTitle(getResources().getString(R.string.notification_title)).build();

    startForeground(uniqueid, notification);

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            onTimerTick();
        }
    }, 0, 500L);

    Log.i(TAG, "Registering event receiver");
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    // Apparently audio registration is persistent across lots of things...
    // restarts, installs, etc.
    mAudioManager.registerMediaButtonEventReceiver(cn);
    // I tried to register this in the manifest, but it doesn't seen to
    // accept it, so I'll do it this way.
    getApplicationContext().registerReceiver(receiver, filter);

    headphoneReceiver = new HeadphoneBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.intent.action.HEADSET_PLUG");
    registerReceiver(headphoneReceiver, filter);
}

From source file:de.dcja.prettygreatmusicplayer.MusicPlaybackService.java

@Override
public synchronized void onCreate() {
    Log.i(TAG, "Music Playback Service Created!");
    isRunning = true;//  w  ww. j  av  a  2  s.c  om
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PGMPWakeLock");

    random = new Random();

    mp = new MediaPlayer();
    mReadaheadThread = new ReadaheadThread();

    mp.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            Log.i(TAG, "Song complete");
            next();
        }

    });

    onDemandMediaMetadataRetriever = new OnDemandMediaMetadataRetriever();

    // https://developer.android.com/training/managing-audio/audio-focus.html
    audioFocusListener = new PrettyGoodAudioFocusChangeListener();

    // Get permission to play audio
    am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

    HandlerThread thread = new HandlerThread("ServiceStartArguments");
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);

    // https://stackoverflow.com/questions/19474116/the-constructor-notification-is-deprecated
    // https://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly/15538209#15538209
    Intent resultIntent = new Intent(this, NowPlaying.class);
    resultIntent.putExtra("From_Notification", true);

    // Use the FLAG_ACTIVITY_CLEAR_TOP to prevent launching a second
    // NowPlaying if one already exists.
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

    Builder builder = new NotificationCompat.Builder(this.getApplicationContext());

    String contentText = getResources().getString(R.string.ticker_text);
    if (songFile != null) {
        contentText = Utils.getPrettySongName(songFile);
    }

    Notification notification = builder.setContentText(contentText).setSmallIcon(R.drawable.ic_pgmp_launcher)
            .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent)
            .setContentTitle(getResources().getString(R.string.notification_title)).build();

    startForeground(uniqueid, notification);

    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            onTimerTick();
        }
    }, 0, 500L);

    Log.i(TAG, "Registering event receiver");
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    // Apparently audio registration is persistent across lots of things...
    // restarts, installs, etc.
    mAudioManager.registerMediaButtonEventReceiver(cn);
    // I tried to register this in the manifest, but it doesn't seen to
    // accept it, so I'll do it this way.
    getApplicationContext().registerReceiver(receiver, filter);

    headphoneReceiver = new HeadphoneBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("android.intent.action.HEADSET_PLUG");
    registerReceiver(headphoneReceiver, filter);
}

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

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

    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/*ww  w . ja v  a 2 s. c o  m*/

            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("MediaPlayer error: " + 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();

    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);

    SharedPreferences prefs = Util.getPreferences(this);
    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);

    instance = this;
    lifecycleSupport.onCreate();

    if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
        getEqualizerController();
    }
}

From source file:ar.com.martineo14.spotifystreamer2.ui.fragment.TrackPlayerActivityFragment.java

public void createMediaPlayer() {
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}

From source file:org.cocos2dx.lib.Cocos2dxMusic.java

/**
 * create mediaplayer for music//  w ww  . ja  v  a  2s  .  c o  m
 * @param path the path relative to assets
 * @return 
 */
private MediaPlayer createMediaplayerFromAssets(String path) {
    MediaPlayer mediaPlayer = new MediaPlayer();

    try {
        if (path.startsWith("/")) {
            mediaPlayer.setDataSource(path);
        } else {
            AssetFileDescriptor assetFileDescritor = mContext.getAssets().openFd(path);
            mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(),
                    assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
        }

        mediaPlayer.prepare();

        mediaPlayer.setVolume(mLeftVolume, mRightVolume);
    } catch (Exception e) {
        mediaPlayer = null;
        Log.e(TAG, "error: " + e.getMessage(), e);
    }

    return mediaPlayer;
}