Example usage for android.media MediaPlayer setOnPreparedListener

List of usage examples for android.media MediaPlayer setOnPreparedListener

Introduction

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

Prototype

public void setOnPreparedListener(OnPreparedListener listener) 

Source Link

Document

Register a callback to be invoked when the media source is ready for playback.

Usage

From source file:Main.java

public static void playSound(Context context, Uri uri) {
    final MediaPlayer player = new MediaPlayer();
    try {/*from  w  w w. j av  a 2  s  .c om*/
        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.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 v  a2s .c  om
    }
    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.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();/*from w  ww . j  a  va2  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.eggwall.SoundSleep.AudioService.java

/**
 * Create a media player with the standard configuration both for white noise and music.
 * @return a generic Media player suitable for this application.
 *//* w  ww. j ava2s  .c  o  m*/
private MediaPlayer getGenericMediaPlayer() {
    final MediaPlayer player = new MediaPlayer();
    // Keep the CPU awake while playing music.
    player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    player.setOnPreparedListener(this);
    return player;
}

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

public void play(int index) {
    mQueue.setCurrent(index);//from  w ww.ja  v a 2 s .co  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 {//from w ww. ja  v a2 s . co 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:fm.krui.kruifm.StreamService.java

/**
 * Prepares the player for streaming and plays the audio upon completion.
 *//*from   w  w  w.j  ava  2 s.  c  om*/
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.yohpapa.research.simplemusicplayer.PlaybackService.java

private MediaPlayer initializePlayer() {
    MediaPlayer player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    player.setOnSeekCompleteListener(this);
    player.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);

    IntentFilter filter = new IntentFilter();
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    registerReceiver(audioOutputChangedEventReceiver, filter);

    return player;
}

From source file:com.bayapps.android.robophish.playback.LocalPlayback.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 ww  w .j av  a2  s  . c o m*/
 */
private MediaPlayer createMediaPlayer(MediaPlayer player) {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (player == null));
    if (player == null) {
        player = 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.
        player.setWakeMode(mContext.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

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

    return player;
}

From source file:com.orange.essentials.otb.ui.OtbTermsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.otb_terms, container, false);
    LinearLayout llayout = (LinearLayout) mView.findViewById(R.id.otb_terms_layout);
    TextView headerTv = (TextView) llayout.findViewById(R.id.otb_header_tv_text);
    headerTv.setText(R.string.otb_home_terms_content);
    List<Term> terms = TrustBadgeManager.INSTANCE.getTerms();

    for (Term term : terms) {
        View layoutToAdd = null;/*from  w  w w .  j  a  va  2  s.  c  o m*/
        if (term.getTermType() == TermType.VIDEO
                && Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
            layoutToAdd = View.inflate(getActivity(), R.layout.otb_terms_video, null);
            TextView titleTv = (TextView) layoutToAdd.findViewById(R.id.otb_term_video_title);
            final AutoResizingFrameLayout anchorView = (AutoResizingFrameLayout) layoutToAdd
                    .findViewById(R.id.videoSurfaceContainer);
            if (mVideoViews == null) {
                mVideoViews = new ArrayList<>();
            }
            mVideoViews.add(anchorView);
            SurfaceView videoSurface = (SurfaceView) layoutToAdd.findViewById(R.id.videoSurface);

            titleTv.setText(term.getTitleId());

            SurfaceHolder videoHolder = videoSurface.getHolder();
            MediaPlayer player = new MediaPlayer();
            if (mPlayers == null) {
                mPlayers = new ArrayList<>();
            }
            mPlayers.add(player);
            final VideoControllerView controller = new VideoControllerView(getContext());
            VideoCallback videoCallback = new VideoCallback(player, controller, anchorView);
            videoHolder.addCallback(videoCallback);
            anchorView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    controller.show();
                    return false;
                }
            });
            try {
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.setDataSource(getContext(), Uri.parse(getString(term.getContentId())));
                player.setOnPreparedListener(videoCallback);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (term.getTermType() == TermType.TEXT) {//TermType.TEXT
            layoutToAdd = View.inflate(getActivity(), R.layout.otb_terms_text, null);
            TextView titleTv = (TextView) layoutToAdd.findViewById(R.id.otb_term_text_title);
            TextView contentTv = (TextView) layoutToAdd.findViewById(R.id.otb_term_text_content);
            titleTv.setText(term.getTitleId());
            contentTv.setText(Html.fromHtml(getString(term.getContentId())));
            contentTv.setMovementMethod(LinkMovementMethod.getInstance());
            contentTv.setLinkTextColor(getResources().getColor(R.color.colorAccent));
        }
        if (null != layoutToAdd) {
            llayout.addView(layoutToAdd);
        }
        if (terms.indexOf(term) != terms.size() - 1) {
            View.inflate(getActivity(), R.layout.otb_separator, llayout);
        }
    }

    return mView;
}