Example usage for android.media MediaPlayer prepareAsync

List of usage examples for android.media MediaPlayer prepareAsync

Introduction

In this page you can find the example usage for android.media MediaPlayer prepareAsync.

Prototype

public native void prepareAsync() throws IllegalStateException;

Source Link

Document

Prepares the player for playback, asynchronously.

Usage

From source file:Main.java

public static void playSound(Context context, Uri uri) {
    final MediaPlayer player = new MediaPlayer();
    try {/*  w ww .  j  a v  a 2  s  .c  o  m*/
        player.setDataSource(context.getApplicationContext(), uri);
        player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                player.release();
            }
        });
        player.prepareAsync();
    } catch (Exception e) {
    }
}

From source file:com.msohm.blackberry.samples.bdvideoplayback.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Initialize BlackBerry Dynamics.
    GDAndroid.getInstance().activityInit(this);
    setContentView(R.layout.activity_main);

    copyButton = (Button) findViewById(R.id.copyButton);

    //The copy button is used to copy an existing video file you have into the secure
    //BlackBerry Dynamics file system.  This only needs to be run once.
    copyButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            //Ensure we have permission to read the file being copied.
            int permissionCheck = ContextCompat.checkSelfPermission(v.getContext(),
                    Manifest.permission.READ_EXTERNAL_STORAGE);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                //Permission isn't set.  Request it.
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[] { Manifest.permission.READ_EXTERNAL_STORAGE },
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
            } else {
                copyFile();/*  w ww.  jav  a  2  s.  c  o m*/
            }
        }
    });

    playButton = (Button) findViewById(R.id.playButton);

    //Initializes the MediaPlayer.
    playButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                if (!isPaused) {
                    BDMediaDataSource source = new BDMediaDataSource(FILENAME);
                    mp.setDataSource(source);
                    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mp.start();
                        }
                    });
                    mp.prepareAsync();
                } else {
                    mp.start();
                }
                isPaused = false;
            } catch (IOException ioex) {
            }

        }
    });

    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
    SurfaceHolder holder = surfaceView.getHolder();
    holder.addCallback(this);
    mp = new MediaPlayer();
    isPaused = false;
}

From source file:com.google.android.apps.forscience.whistlepunk.metadata.TriggerHelper.java

public void doAudioAlert(Context context) {
    // Use a throttler to keep this from interrupting itself too much.
    if (System.currentTimeMillis() - mLastAudioMs < THROTTLE_LIMIT_MS) {
        return;/*  w w w  .j  a va 2 s .  c o m*/
    }
    mLastAudioMs = System.currentTimeMillis();
    final MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        mediaPlayer.setDataSource(context, mNotification);
        mediaPlayer.setOnPreparedListener(MEDIA_PLAYER_ON_PREPARED_LISTENER);
        mediaPlayer.setOnCompletionListener(MEDIA_PLAYER_COMPLETION_LISTENER);
        // Don't prepare the mediaplayer on the UI thread! That's asking for trouble.
        mediaPlayer.prepareAsync();
    } catch (IOException e) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "error getting notification sound");
        }
    }
}

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

public void play(int index) {
    mQueue.setCurrent(index);/*www.  j  ava 2s .  c o m*/
    Song song = mQueue.getCurrent();

    Intent intent = new Intent(EVENT_PLAYING);
    intent.putExtra(DATA_SONG, song);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    broadcastPlayState(PlayState.PLAYING);

    Log.d("fiction", "Playing new song");
    try {
        MediaPlayer nextMediaPlayer = new MediaPlayer();
        nextMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        nextMediaPlayer.setDataSource(getApplicationContext(), song.getUri());
        nextMediaPlayer.setOnPreparedListener(this);
        nextMediaPlayer.prepareAsync();
    } catch (IOException e) {
    }
}

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

private boolean preparePlayer(final MediaPlayer player, boolean current) {
    player.setOnPreparedListener(this);
    player.setOnBufferingUpdateListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    try {//  w w  w  .  j a  v a 2  s  . c o m
        player.prepareAsync();
        if (current) {
            setState(STATE_PREPARING);
        }
    } catch (IllegalStateException e) {
        if (current) {
            setError(Listener.ERROR_PREPARE_ERROR, 0, null, e);
        }
        return false;
    }
    return true;
}

From source file:org.dharmaseed.android.PlayTalkActivity.java

public void playTalkButtonClicked(View view) {
    Log.d(LOG_TAG, "button pressed");
    MediaPlayer mediaPlayer = talkPlayerFragment.getMediaPlayer();
    if (mediaPlayer.isPlaying()) {
        mediaPlayer.pause();//w ww.  j a v a  2  s  .c o  m
        setPPButton("ic_media_play");
    } else if (talkPlayerFragment.getMediaPrepared()) {
        mediaPlayer.start();
        setPPButton("ic_media_pause");
    } else {
        try {
            if (talk.isDownloaded()) {
                Log.d(LOG_TAG, "Playing from " + talk.getPath());
                mediaPlayer.setDataSource(talk.getPath());
            } else {
                mediaPlayer.setDataSource(talk.getAudioUrl());
            }
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            Log.e(LOG_TAG, e.toString());
        }
    }
}

From source file:fm.krui.kruifm.StreamService.java

/**
 * Prepares the player for streaming and plays the audio upon completion.
 *//*from  w w  w  .  ja  v  a 2 s .co m*/
private void prepareAudio() {
    try {
        Log.v(TAG, "Attempting to play stream from " + streamUrl);
        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {

                // When the stream is buffered, kill prompt and start playing automatically.
                mp.start();
                isPrepared = true;

                // Clear cached track information and start audio service.
                setCurrentTrackInfo("", "", "");
                updateNotification("", "", true);
                setUpdateTimer(true);

                // Since we're not buffering anymore, hide the status bar from the user
                broadcastMessage(BROADCAST_COMMAND_STATUS_HIDE);
                Log.i(TAG, "Stream playback started.");

            }
        });

        // Prepares stream without blocking UI Thread
        mp.prepareAsync();
        updateStreamStatus(getString(R.string.stream_status_buffering), true);

    } catch (IllegalStateException e) {
        Log.e(TAG, "Caught IllegalStateException when preparing: ");
        e.printStackTrace();
    }
}

From source file:com.bayapps.android.robophish.playback.LocalPlayback.java

public boolean playNext(QueueItem item) {
    MediaPlayer nextPlayer;
    if (mMediaPlayer == mMediaPlayerA) {
        nextPlayer = mMediaPlayerB;/*from  ww w .ja v  a 2 s. c  om*/
    } else
        nextPlayer = mMediaPlayerA;

    String mediaId = item.getDescription().getMediaId();
    boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
    if (mediaHasChanged) {
        mNextMediaId = mediaId;
    }

    MediaMetadataCompat track = mMusicProvider
            .getMusic(MediaIDHelper.extractMusicIDFromMediaID(item.getDescription().getMediaId()));

    //noinspection ResourceType
    String source = track.getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE);

    nextPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
        nextPlayer.setDataSource(source);
    } catch (IOException ex) {
        LogHelper.e(TAG, ex, "Exception playing song");
        if (mCallback != null) {
            mCallback.onError(ex.getMessage());
        }
    }

    // Starts preparing the media player in the background. When
    // it's done, it will call our OnPreparedListener (that is,
    // the onPrepared() method on this class, since we set the
    // listener to 'this'). Until the media player is prepared,
    // we *cannot* call start() on it!
    nextPlayer.prepareAsync();

    mMediaPlayersSwapping = true;
    return true;
}

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

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {//from   w  w w  .j  a  va  2s  .  c om
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        String dataSource = file.getPath();
        if (isPartial) {
            if (proxy == null) {
                proxy = new StreamProxy(this);
                proxy.start();
            }
            dataSource = String.format("http://127.0.0.1:%d/%s", proxy.getPort(),
                    URLEncoder.encode(dataSource, Constants.UTF_8));
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadServiceImpl.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        if (start) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);
                        } else {
                            setPlayerState(PAUSED);
                        }
                    }

                    lifecycleSupport.serializeDownloadQueue();
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}

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

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {//from ww w.jav a2  s.  com
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        boolean isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        String dataSource = file.getAbsolutePath();
        if (isPartial && !Util.isOffline(this)) {
            if (proxy == null) {
                proxy = new BufferProxy(this);
                proxy.start();
            }
            proxy.setBufferFile(downloadFile);
            dataSource = proxy.getPrivateAddress(dataSource);
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}