List of usage examples for android.media MediaPlayer start
public void start() throws IllegalStateException
From source file:audio.lisn.adapter.StoreBookViewAdapter.java
private void playPreview() { isLoadingPreview = true;//ww w. j ava 2 s .c o m isPlayingPreview = false; pausePlayer(); notifyDataSetChanged(); if (connectionDetector.isConnectingToInternet()) { if (mediaPlayer == null) { mediaPlayer = new MediaPlayer(); } if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); if (timerUpdateThread != null) { timerUpdateThread.interrupt(); } } mediaPlayer.reset(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(selectedAudioBook.getPreview_audio()); } catch (IOException e) { Log.v("playPreview", "IOException" + e.getMessage()); e.printStackTrace(); } mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mp) { isPlayingPreview = true; isLoadingPreview = false; startTimer(); mp.start(); notifyDataSetChanged(); } }); mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { public boolean onError(MediaPlayer mp, int what, int extra) { notifyDataSetChanged(); String msg = ""; if (extra == MediaPlayer.MEDIA_ERROR_IO) { msg = "MEDIA_ERROR_IO"; } else if (extra == MediaPlayer.MEDIA_ERROR_MALFORMED) { msg = "MEDIA_ERROR_MALFORMED"; } else if (extra == MediaPlayer.MEDIA_ERROR_UNSUPPORTED) { msg = "MEDIA_ERROR_UNSUPPORTED"; } else if (extra == MediaPlayer.MEDIA_ERROR_TIMED_OUT) { msg = "MEDIA_ERROR_TIMED_OUT"; } else { msg = "video_error_unknown_error"; } showErrorMessage(msg); return false; } }); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { isPlayingPreview = false; isLoadingPreview = false; stopTimer(); notifyDataSetChanged(); } }); try { mediaPlayer.prepareAsync(); // prepare async to not block main } catch (Exception e) { showErrorMessage(e.getMessage()); isPlayingPreview = false; isLoadingPreview = false; stopTimer(); notifyDataSetChanged(); } } else { AlertDialog.Builder builder = new AlertDialog.Builder(selectedView.getContext()); builder.setTitle(R.string.NO_INTERNET_TITLE).setMessage(R.string.NO_INTERNET_MESSAGE) .setPositiveButton(R.string.BUTTON_OK, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // FIRE ZE MISSILES! } }); AlertDialog dialog = builder.create(); dialog.show(); } }
From source file:com.baruckis.nanodegree.spotifystreamer.PlayerService.java
@Override public void onPrepared(MediaPlayer mediaPlayer) { mIsError = false;/*from w w w . ja v a2 s. co m*/ mIsPrepared = true; // if user has not pressed pause button before new track was prepared to play... if (!isPlaybackPausedByUser) { // ...then start playback mediaPlayer.start(); } // Inform UI that track is prepared to be played. if (mListener != null) { mListener.onTrackPrepared(); } }
From source file:hku.fyp14017.blencode.ui.controller.SoundController.java
public void startSound(SoundInfo soundInfo, MediaPlayer mediaPlayer) { if (!soundInfo.isPlaying) { try {/*from ww w .j a v a 2s. co m*/ mediaPlayer.reset(); mediaPlayer.setDataSource(soundInfo.getAbsolutePath()); mediaPlayer.prepare(); mediaPlayer.start(); soundInfo.isPlaying = true; } catch (IOException ioException) { Log.e(TAG, "Cannot start sound.", ioException); } } }
From source file:com.hybris.mobile.lib.location.geofencing.service.GeofencingIntentService.java
/** * Send a notification when a geofence is triggered * * @param geofence the geofence triggered * @param notification the notification object * @param geofenceTransition the geofence transition type *//* w ww. j a v a 2 s .co m*/ protected void sendNotification(Geofence geofence, GeofenceObject.Notification notification, int geofenceTransition) { if (notification != null) { // Notification String notificationContentTitle = notification.getNotificationTitle(); String notificationContentText = notification.getNotificationText(); int notificationIconResId = notification.getNotificationIconResId(); Notification.Builder builder = new Notification.Builder(this); builder.setContentTitle(notificationContentTitle).setContentText(notificationContentText); if (notificationIconResId > 0) { builder.setSmallIcon(notificationIconResId); } try { // Intent on click on the notification if (StringUtils.isNotBlank(notification.getIntentClassDestination())) { Class<?> intentClassDestination = Class.forName(notification.getIntentClassDestination()); // Create an explicit content Intent that starts the Activity defined in intentClassDestination Intent notificationIntent = new Intent(this, intentClassDestination); // Geofence Id to pass to the activity in order to retrieve the object if (notification.getIntentBundle() != null) { GeofenceObject.IntentBundle intentBundle = notification.getIntentBundle(); notificationIntent.putExtra(intentBundle.getKeyName(), intentBundle.getBundle()); // Easter egg :) if (intentBundle.getBundle().getBoolean(GeofencingConstants.EXTRA_PLAY_SOUND)) { MediaPlayer mediaPlayer; if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) { Log.d(TAG, "Playing entering geofence sound"); mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.entering_geofence); } else { Log.d(TAG, "Playing exiting geofence sound"); mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.leaving_geofence); } mediaPlayer.start(); } } PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, geofence.getRequestId().hashCode(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(notificationPendingIntent); } } catch (ClassNotFoundException e) { Log.e(TAG, "Unable to find class " + notification.getIntentClassDestination() + "." + e.getLocalizedMessage()); } // Constructing the Notification and setting the flag to auto remove the notification when the user click on it Notification notificationView; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { notificationView = builder.build(); } else { notificationView = builder.getNotification(); } notificationView.flags = Notification.FLAG_AUTO_CANCEL; notificationView.defaults = Notification.DEFAULT_ALL; // Get an instance of the Notification manager NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); // Issue the notification mNotificationManager.notify(UUID.randomUUID().toString().hashCode(), notificationView); } else { Log.e(TAG, "Notification empty for Geofence " + geofence); } }
From source file:com.irccloud.android.activity.VideoPlayerActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.ImageViewerTheme);// ww w. j av a 2 s. com if (savedInstanceState == null) overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out); setContentView(R.layout.activity_video_player); toolbar = findViewById(R.id.toolbar); try { setSupportActionBar(toolbar); } catch (Throwable t) { } if (Build.VERSION.SDK_INT < 21) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } else if (Build.VERSION.SDK_INT >= 21) { Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.splash_logo); if (cloud != null) { setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name), cloud, getResources().getColor(android.R.color.black))); } getWindow().setStatusBarColor(getResources().getColor(android.R.color.black)); getWindow().setNavigationBarColor(getResources().getColor(android.R.color.black)); if (Build.VERSION.SDK_INT >= 23) { getWindow().getDecorView().setSystemUiVisibility( getWindow().getDecorView().getSystemUiVisibility() & ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); } } getSupportActionBar().setDisplayHomeAsUpEnabled(true); if (Build.VERSION.SDK_INT > 16) { getWindow().getDecorView() .setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onSystemUiVisibilityChange(int visibility) { if ((visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { toolbar.setAlpha(0); toolbar.animate().alpha(1); controls.setAlpha(0); controls.animate().alpha(1); hide_actionbar(); } else { toolbar.setAlpha(1); toolbar.animate().alpha(0); controls.setAlpha(1); controls.animate().alpha(0); } } }); } controls = findViewById(R.id.controls); mProgress = findViewById(R.id.progress); rew = findViewById(R.id.rew); rew.setEnabled(false); rew.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { handler.removeCallbacks(mHideRunnable); handler.post(rewindRunnable); } if (motionEvent.getAction() == MotionEvent.ACTION_UP) { handler.removeCallbacks(rewindRunnable); hide_actionbar(); } return false; } }); play = findViewById(R.id.play); play.setEnabled(false); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { video.start(); handler.post(mUpdateRunnable); hide_actionbar(); } }); pause = findViewById(R.id.pause); pause.setEnabled(false); pause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { video.pause(); handler.post(mUpdateRunnable); handler.removeCallbacks(mHideRunnable); } }); ffwd = findViewById(R.id.ffwd); ffwd.setEnabled(false); ffwd.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { handler.removeCallbacks(mHideRunnable); handler.post(ffwdRunnable); } if (motionEvent.getAction() == MotionEvent.ACTION_UP) { handler.removeCallbacks(ffwdRunnable); hide_actionbar(); } return false; } }); time_current = findViewById(R.id.time_current); time = findViewById(R.id.time); seekBar = findViewById(R.id.mediacontroller_progress); seekBar.setEnabled(false); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { video.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { if (video.isPlaying()) video.pause(); handler.removeCallbacks(mHideRunnable); } @Override public void onStopTrackingTouch(SeekBar seekBar) { hide_actionbar(); } }); video = findViewById(R.id.video); video.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (Build.VERSION.SDK_INT > 16) { if ((getWindow().getDecorView().getSystemUiVisibility() & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } else { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); hide_actionbar(); } } else { if (toolbar.getVisibility() == View.VISIBLE) { toolbar.setVisibility(View.GONE); controls.setVisibility(View.GONE); } else { toolbar.setVisibility(View.VISIBLE); controls.setVisibility(View.VISIBLE); hide_actionbar(); } } return false; } }); video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); mProgress.setVisibility(View.GONE); rew.setEnabled(true); pause.setEnabled(true); play.setEnabled(true); ffwd.setEnabled(true); seekBar.setEnabled(true); handler.post(mUpdateRunnable); hide_actionbar(); } }); video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { video.pause(); video.seekTo(video.getDuration()); handler.removeCallbacks(mHideRunnable); if (Build.VERSION.SDK_INT > 16) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); } else { toolbar.setVisibility(View.VISIBLE); controls.setVisibility(View.VISIBLE); } } }); video.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mediaPlayer, int i, int i1) { AlertDialog d = new AlertDialog.Builder(VideoPlayerActivity.this).setTitle("Playback Failed") .setMessage("An error occured while trying to play this video") .setPositiveButton("Download", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (Build.VERSION.SDK_INT >= 16 && ActivityCompat.checkSelfPermission( VideoPlayerActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(VideoPlayerActivity.this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0); } else { DownloadManager d = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); if (d != null) { DownloadManager.Request r = new DownloadManager.Request( Uri.parse(getIntent().getDataString().replace( getResources().getString(R.string.VIDEO_SCHEME), "http"))); r.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); r.allowScanningByMediaScanner(); d.enqueue(r); } } } }).setNegativeButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }).create(); d.show(); return true; } }); if (getIntent() != null && getIntent().getDataString() != null) { Uri url = Uri.parse( getIntent().getDataString().replace(getResources().getString(R.string.VIDEO_SCHEME), "http")); if (url.getHost().endsWith("facebook.com")) { new FacebookTask().execute(url); } else { video.setVideoURI(url); } Answers.getInstance().logContentView(new ContentViewEvent().putContentType("Video")); } else { finish(); } }
From source file:edu.northwestern.cbits.activitydetector.app.MainActivity.java
private void UpdateGUI() { i++;/*from w w w . j a v a 2 s . c o m*/ final MainActivity me = this; // Runs once a second mHandler.post(new Runnable() { public void run() { Log.d(getString(R.string.app_name), ActivityRecognitionIntentService.ACTIVITY_NAME); nameView.setText( ActivityRecognitionIntentService.ACTIVITY_NAME + " " + System.currentTimeMillis() / 1000); //setting up tone for on_foot Uri defaultRingtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); MediaPlayer mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(me, defaultRingtoneUri); mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION); mediaPlayer.prepare(); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); if (ActivityRecognitionIntentService.ACTIVITY_NAME == "on_foot") { mediaPlayer.start(); } else { mediaPlayer.release(); } } catch (IOException e) { e.printStackTrace(); } ; } }); }
From source file:net.wespot.pim.view.InqImageDetailFragment.java
public void playPauseButton() { if (status == PAUSE) { playPauseButton/*from www .j a v a2 s . c om*/ .setImageDrawable(getActivity().getResources().getDrawable(android.R.drawable.ic_media_pause)); status = PLAYING; mediaPlayer.start(); finalTime = mediaPlayer.getDuration(); startTime = mediaPlayer.getCurrentPosition(); if (oneTimeOnly == 0) { seekbar.setMax((int) finalTime); oneTimeOnly = 1; } seekbar.setProgress((int) startTime); playHandler.postDelayed(UpdateSongTime, 100); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { status = PAUSE; playPauseButton.setImageDrawable( getActivity().getResources().getDrawable(android.R.drawable.ic_media_play)); } }); } else { playPauseButton .setImageDrawable(getActivity().getResources().getDrawable(android.R.drawable.ic_media_play)); status = PAUSE; mediaPlayer.pause(); } }
From source file:com.android.onemedia.playback.LocalRenderer.java
/** * Seek to a given position in the media. If the seek succeeded or will be * performed when loading is complete returns true. If the position is not * in range or the player will never be ready returns false. * * @param position The position to seek to in milliseconds * @return true if playback was moved or will be moved when ready *//* ww w.j av a 2 s .c om*/ @Override public boolean onSeekTo(int position) { MediaPlayer player = mPlayer; if (player != null && (mState & CAN_SEEK) != 0) { if (position < 0 || position >= getDuration()) { return false; } else { if (mState == STATE_ENDED) { player.start(); player.pause(); setState(STATE_PAUSED); } player.seekTo(position); } } else if ((mState & CAN_READY_SEEK) != 0) { mSeekOnReady = position; } else { return false; } return true; }
From source file:ac.robinson.paperchains.PaperChainsActivity.java
private void streamAudio(String audioPath) { resetAudioPlayer();/*from w ww. j av a2 s . c o m*/ mPlayButton.setVisibility(View.VISIBLE); // undo invisible by resetAudioPlayer(); mPlayButton.setImageResource(R.drawable.ic_refresh_white_24dp); mPlayButton.startAnimation(mRotateAnimation); mAudioPlayer = new MediaPlayer(); mAudioPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { try { // slightly hacky way of detecting whether the path is a url or a file, and handling appropriately new URL(audioPath); // only for the exception it throws mAudioPlayer.setDataSource(audioPath); } catch (MalformedURLException e) { FileInputStream inputStream = new FileInputStream(audioPath); mAudioPlayer.setDataSource(inputStream.getFD()); inputStream.close(); } mAudioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); mPlayButton.clearAnimation(); mPlayButton.setImageResource(R.drawable.ic_pause_white_24dp); } }); mAudioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mPlayButton.clearAnimation(); mPlayButton.setImageResource(R.drawable.ic_play_arrow_white_24dp); } }); mAudioPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { streamAudioLoadFailed(R.string.hint_soundcloud_load_failed); return true; } }); mAudioPlayer.prepareAsync(); } catch (IOException e) { streamAudioLoadFailed(R.string.hint_soundcloud_load_failed); } }
From source file:com.android.onemedia.playback.LocalRenderer.java
/** * Start the player if possible or queue it to play when ready. If the * player is in a state where it will never be ready returns false. * * @return true if the content was started or will be started later *//*from www .j a v a 2 s .co m*/ @Override public boolean onPlay() { MediaPlayer player = mPlayer; if (player != null && mState == STATE_PLAYING) { // already playing, just return return true; } if (!mHasAudioFocus) { requestAudioFocus(); } if (player != null && canPlay()) { player.start(); setState(STATE_PLAYING); } else if (canReadyPlay()) { mPlayOnReady = true; } else if (!isPlaying()) { return false; } return true; }