List of usage examples for android.media MediaPlayer MediaPlayer
public MediaPlayer()
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 v a2 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.customprogrammingsolutions.MediaStreamer.MediaStreamerService.java
private void play() { Log.i(TAG, "MediaStreamerService.play()"); isPreparing = true;/*from w w w. java 2 s.c om*/ startNotification(); if (!requestAudioFocus()) { Log.i(TAG, "MediaStreamerService.play() - AudioFocus request denied"); notifyStreamError(AUDIO_FOCUS_DENIED_ERROR); } mMediaPlayer = new MediaPlayer(); mMediaPlayer.setOnErrorListener(this); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setVolume(1.0f, 1.0f); try { mMediaPlayer.setDataSource(this, Uri.parse(urlToStream)); } catch (Exception e) { Log.e(TAG, "MediaStreamerService.play() - Error setting data source for the media player", e); stop(); notifyStreamError(MEDIA_PLAYER_ERROR); return; } try { mMediaPlayer.prepareAsync(); // prepare async to not block main thread } catch (Exception e) { Log.e(TAG, "MediaStreamerService.play() - Error preparing the media player", e); stop(); notifyStreamError(MEDIA_PLAYER_ERROR); return; } }
From source file:edu.stanford.mobisocial.dungbeetle.obj.action.PlayAllAudioAction.java
public void playNextSong() { if (c.isAfterLast()) { c.close();/*w ww . jav a 2s. c o m*/ alert.dismiss(); return; } try { final JSONObject objData = new JSONObject(c.getString(c.getColumnIndex(DbObject.JSON))); Runnable r = new Runnable() { @Override public void run() { Log.w("PlayAllAudioAction", objData.optString("feedName")); byte bytes[] = Base64.decode(objData.optString(VoiceObj.DATA), Base64.DEFAULT); File file = new File(getTempFilename()); try { OutputStream os = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(os); bos.write(bytes, 0, bytes.length); bos.flush(); bos.close(); copyWaveFile(getTempFilename(), getFilename()); deleteTempFile(); mp = new MediaPlayer(); mp.setDataSource(getFilename()); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer m) { Log.w("PlayAllAudioAction", "finished"); c.moveToNext(); playNextSong(); } }); mp.prepare(); mp.start(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; if (context instanceof Activity) { ((Activity) context).runOnUiThread(r); } else { r.run(); } } catch (Exception e) { } }
From source file:com.somexapps.wyre.services.MediaService.java
private void initMediaSessions() { // Initialize player mediaPlayer = new MediaPlayer(); // Add listener to handle completion of song mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override/* ww w. ja v a 2 s .com*/ public void onCompletion(MediaPlayer mp) { // Send intent to play next song in MediaService list Intent nextSong = new Intent(getApplicationContext(), MediaService.class); nextSong.setAction(ACTION_NEXT); startService(nextSong); } }); // Set up session and controller // Create the media session mediaSession = new MediaSessionCompat(this, MEDIA_SESSION_TAG, mediaSessionComponentName, null); // Set up controller try { mediaController = new MediaControllerCompat(getApplicationContext(), mediaSession.getSessionToken()); } catch (RemoteException e) { Log.e(TAG, "Unable to set up media controller: " + e.getMessage()); } // Set up callbacks for media session mediaSession.setCallback(new MediaSessionCompat.Callback() { @Override public void onPlay() { super.onPlay(); Log.d(TAG, "Playing media"); buildNotification(generateAction(R.drawable.ic_pause_white_36dp, getString(R.string.media_service_notification_pause), ACTION_PAUSE)); } @Override public void onPause() { super.onPause(); Log.d(TAG, "Pausing media"); buildNotification(generateAction(R.drawable.ic_play_arrow_white_36dp, getString(R.string.media_service_notification_play), ACTION_PLAY)); } @Override public void onSkipToNext() { super.onSkipToNext(); Log.d(TAG, "Skipping to next song"); // Update the notification with the next song info buildNotification(generateAction(R.drawable.ic_pause_white_36dp, getString(R.string.media_service_notification_pause), ACTION_PAUSE)); } @Override public void onSkipToPrevious() { super.onSkipToPrevious(); Log.d(TAG, "Skipping to previous song"); // Update the notification with the previous song info buildNotification(generateAction(R.drawable.ic_pause_white_36dp, getString(R.string.media_service_notification_pause), ACTION_PAUSE)); } @Override public void onFastForward() { super.onFastForward(); } @Override public void onRewind() { super.onRewind(); } @Override public void onStop() { super.onStop(); } @Override public void onSeekTo(long pos) { super.onSeekTo(pos); } @Override public void onSetRating(RatingCompat rating) { super.onSetRating(rating); } }); }
From source file:org.hansel.myAlert.ReminderService.java
private void playSound() { mMediaPlayer = new MediaPlayer(); try {// w w w. j av a 2 s .com mMediaPlayer.setDataSource(getApplicationContext(), Uri.parse(Util.getRingtone(getApplicationContext()))); final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) { mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mMediaPlayer.prepare(); mMediaPlayer.setLooping(true); mMediaPlayer.start(); } } catch (IOException e) { System.out.println("Error tocando alarma"); } }
From source file:com.andreadec.musicplayer.MusicService.java
/** * Called when the service is created./*from w w w. j ava 2 s. c om*/ */ @Override public void onCreate() { PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MusicServiceWakelock"); // Initialize the telephony manager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); phoneStateListener = new MusicPhoneStateListener(); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Initialize pending intents quitPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.quit"), 0); previousPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.previous"), 0); playpausePendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.playpause"), 0); nextPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.next"), 0); pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_UPDATE_CURRENT); // Read saved user preferences preferences = PreferenceManager.getDefaultSharedPreferences(this); // Initialize the media player mediaPlayer = new MediaPlayer(); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK); // Enable the wake lock to keep CPU running when the screen is switched off shuffle = preferences.getBoolean(Constants.PREFERENCE_SHUFFLE, Constants.DEFAULT_SHUFFLE); repeat = preferences.getBoolean(Constants.PREFERENCE_REPEAT, Constants.DEFAULT_REPEAT); repeatAll = preferences.getBoolean(Constants.PREFERENCE_REPEATALL, Constants.DEFAULT_REPEATALL); try { // This may fail if the device doesn't support bass boost bassBoost = new BassBoost(1, mediaPlayer.getAudioSessionId()); bassBoost.setEnabled( preferences.getBoolean(Constants.PREFERENCE_BASSBOOST, Constants.DEFAULT_BASSBOOST)); setBassBoostStrength(preferences.getInt(Constants.PREFERENCE_BASSBOOSTSTRENGTH, Constants.DEFAULT_BASSBOOSTSTRENGTH)); bassBoostAvailable = true; } catch (Exception e) { bassBoostAvailable = false; } try { // This may fail if the device doesn't support equalizer equalizer = new Equalizer(1, mediaPlayer.getAudioSessionId()); equalizer.setEnabled( preferences.getBoolean(Constants.PREFERENCE_EQUALIZER, Constants.DEFAULT_EQUALIZER)); setEqualizerPreset( preferences.getInt(Constants.PREFERENCE_EQUALIZERPRESET, Constants.DEFAULT_EQUALIZERPRESET)); equalizerAvailable = true; } catch (Exception e) { equalizerAvailable = false; } random = new Random(System.nanoTime()); // Necessary for song shuffle shakeListener = new ShakeListener(this); if (preferences.getBoolean(Constants.PREFERENCE_SHAKEENABLED, Constants.DEFAULT_SHAKEENABLED)) { shakeListener.enable(); } telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); // Start listen for telephony events // Inizialize the audio manager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName()); audioManager.registerMediaButtonEventReceiver(mediaButtonReceiverComponent); audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); // Initialize remote control client if (Build.VERSION.SDK_INT >= 14) { icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); mediaButtonIntent.setComponent(mediaButtonReceiverComponent); PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0); remoteControlClient = new RemoteControlClient(mediaPendingIntent); remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT); audioManager.registerRemoteControlClient(remoteControlClient); } updateNotificationMessage(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.andreadec.musicplayer.quit"); intentFilter.addAction("com.andreadec.musicplayer.previous"); intentFilter.addAction("com.andreadec.musicplayer.previousNoRestart"); intentFilter.addAction("com.andreadec.musicplayer.playpause"); intentFilter.addAction("com.andreadec.musicplayer.next"); intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("com.andreadec.musicplayer.quit")) { sendBroadcast(new Intent("com.andreadec.musicplayer.quitactivity")); stopSelf(); return; } else if (action.equals("com.andreadec.musicplayer.previous")) { previousItem(false); } else if (action.equals("com.andreadec.musicplayer.previousNoRestart")) { previousItem(true); } else if (action.equals("com.andreadec.musicplayer.playpause")) { playPause(); } else if (action.equals("com.andreadec.musicplayer.next")) { nextItem(); } else if (action.equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) { if (preferences.getBoolean(Constants.PREFERENCE_STOPPLAYINGWHENHEADSETDISCONNECTED, Constants.DEFAULT_STOPPLAYINGWHENHEADSETDISCONNECTED)) { pause(); } } } }; registerReceiver(broadcastReceiver, intentFilter); if (!isPlaying()) { loadLastSong(); } startForeground(Constants.NOTIFICATION_MAIN, notification); }
From source file:edu.chl.dat255.sofiase.readyforapet.viewcontroller.PetActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.petactivity); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Receiving the new or saved pet if (CreatePetActivity.getPet() != null) { dog = (Dog) CreatePetActivity.getPet(); } else {/*from w w w.j a v a2 s .c om*/ try { dog = (Dog) Pet.load("pet_file.dat", PetActivity.this); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //Getting the petMood petMood = dog.getPetMood(); //Getting the pet name petName = dog.getName(); //Connecting variables to xml objects play = (Button) findViewById(R.id.play); walk = (Button) findViewById(R.id.walk); eat = (Button) findViewById(R.id.eat); sleep = (Button) findViewById(R.id.sleep); showPetAge = (TextView) findViewById(R.id.petage); petResponse = (TextView) findViewById(R.id.petresponse); dogBiscuit = (ImageView) findViewById(R.id.dogbiscuit); dogPicture = (ImageView) findViewById(R.id.dogpicture); dogBiscuit.setVisibility(View.GONE); dogPicture.setVisibility(View.VISIBLE); //Initializing the background music try { afd = getAssets().openFd("readyforapetsong6.m4v"); player = new MediaPlayer(); player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); player.setLooping(true); player.prepare(); player.start(); } catch (IOException e) { e.printStackTrace(); } //Making it possible to turn off music with a checkbox addListenerOnMusic(); musicCheckBox.setChecked(true); //Getting the age of the pet if it has not already died petAge = (int) (petMood.getCurrentHour() - dog.getBirthHour()) / 24; //Setting textview with welcome message petResponse.setText("Hello, my name is " + petName + "!"); petResponse.setVisibility(View.VISIBLE); uiHandler.postDelayed(makeTextGone, 2500); //Setting textview with current age of the pet showPetAge.setText(petName + " is " + petAge + " days old."); petResponse.setVisibility(View.VISIBLE); //Changing the picture and enabling/disabling buttons depending on mood changePicture(); //Decreasing the moodBar depending on how much time has passed since last eat, walk, play and sleep petMood.setFoodMood(petMood.getFoodMood() + petMood.moodBarDecrease(petMood.getLastEatHour(), petMood.getCurrentHour())); petMood.setWalkMood(petMood.getWalkMood() + petMood.moodBarDecrease(petMood.getLastWalkHour(), petMood.getCurrentHour())); petMood.setPlayMood(petMood.getPlayMood() + petMood.moodBarDecrease(petMood.getLastPlayHour(), petMood.getCurrentHour())); petMood.setSleepMood(petMood.getSleepMood() + petMood.moodBarDecrease(petMood.getLastSleepHour(), petMood.getCurrentHour())); moodBar = (ProgressBar) findViewById(R.id.moodbar); moodBar.setProgress(petMood.getSumMood()); eat.setOnClickListener(new OnClickListener() { /** * Making the dog feel less hungry if it is hungry and else give the message i'm full. * Also shows a picture of a dogbisquit when eating. * * @param v - View */ @Override public void onClick(View v) { petResponse = (TextView) findViewById(R.id.petresponse); //Disabling buttons when eating if (petMood.getFoodMood() < 5) { play.setEnabled(false); eat.setEnabled(false); walk.setEnabled(false); sleep.setEnabled(false); new Handler().postDelayed(new Runnable() { @Override public void run() { eat.setEnabled(true); walk.setEnabled(true); play.setEnabled(true); sleep.setEnabled(true); changePicture(); } }, 10000); //Getting the pet response of eating petResponse.setText(dog.eat()); petResponse.setVisibility(View.VISIBLE); uiHandler.postDelayed(makeTextGone, 10000); dogBiscuit.setVisibility(View.VISIBLE); dogBiscuit.setBackgroundResource(R.anim.animation); //Starting animation eating dogbisquit final AnimationDrawable anim = (AnimationDrawable) dogBiscuit.getBackground(); anim.start(); uiHandler.postDelayed(makeTextGone, 10000); } else { petResponse.setText(dog.eat()); petResponse.setVisibility(View.VISIBLE); uiHandler.postDelayed(makeTextGone, 5000); } //Updating the moodbar moodBar = (ProgressBar) findViewById(R.id.moodbar); moodBar.setProgress(petMood.getSumMood()); } }); play.setOnClickListener(new OnClickListener() { /** * Sends the user to PlayActivity if the pet is not too hungry. * * @param v - View */ @Override public void onClick(View v) { //Continuing to playActivity only of the dog has not died and is not too hungry if ((petMood.getPlayMood() < 5 && petMood.getFoodMood() >= 3) && dog.isAlive()) { //Opening PlayActivity and receives a requestCode when resuming this activity PetActivity.this.startActivityForResult(new Intent(PetActivity.this, PlayActivity.class), 0); } else { petResponse.setText(dog.play(0)); petResponse.setVisibility(View.VISIBLE); uiHandler.postDelayed(makeTextGone, 2000); } changePicture(); } }); walk.setOnClickListener(new OnClickListener() { /** * Sends the user to WalkActivity if the pet wants to walk. * When resuming PetActivity a result is received that tells how far the pet walked. * * @param v - View */ @Override public void onClick(View v) { petResponse = (TextView) findViewById(R.id.petresponse); // Moving to the WalkActivity class if foodMood is high enough and petMood is below 5. if (((petMood.getFoodMood() < 3 && petMood.getWalkMood() < 5) || petMood.getWalkMood() == 5)) { petResponse.setText(dog.walk(0)); petResponse.setVisibility(View.VISIBLE); uiHandler.postDelayed(makeTextGone, 2000); } else if (dog.isAlive()) { //Opening PlayActivity and receives a requestCode when resuming this activity PetActivity.this.startActivityForResult(new Intent(PetActivity.this, WalkActivity.class), 1); } else { petResponse.setText(dog.walk(0)); petResponse.setVisibility(View.VISIBLE); uiHandler.postDelayed(makeTextGone, 2000); } changePicture(); } }); sleep.setOnClickListener(new OnClickListener() { /** * Sending the user to SleepActivity if sleepMood is below 5. * When resuming PetActivity a result is received that tells how much the pet has slept. * * @param v - View */ @Override public void onClick(View v) { if (dog.isAlive() && petMood.getSleepMood() < 5) { //Opening PlayActivity if the dog is alive and receives a requestCode when resuming this activity PetActivity.this.startActivityForResult(new Intent(PetActivity.this, SleepActivity.class), 2); } else { //Set the pet's response if it is either dead or not sleepy petResponse = (TextView) findViewById(R.id.petresponse); petResponse.setText(dog.sleep(0)); petResponse.setVisibility(View.VISIBLE); uiHandler.postDelayed(makeTextGone, 2000); } changePicture(); } }); }
From source file:com.brodev.socialapp.view.MusicPlaySong.java
/** This method initialise all the views in project */ private void initView() { buttonPlayPause = (ImageButton) findViewById(R.id.buttonPlayPause); buttonPlayPause.setOnClickListener(this); seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay); seekBarProgress.setMax(99); // It means 100% .0-99 seekBarProgress.setOnTouchListener(this); mediaPlayer = new MediaPlayer(); mediaPlayer.setOnBufferingUpdateListener(this); mediaPlayer.setOnCompletionListener(this); try {//from ww w. ja v a 2 s . co m mediaPlayer.setDataSource(music.getSong_path()); // setup song from // http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 // URL to // mediaplayer // data source mediaPlayer.prepareAsync(); // you must call this method after setup // the datasource in setDataSource // method. After calling prepare() the // instance of MediaPlayer starts load // data from URL to internal buffer. } catch (Exception e) { e.printStackTrace(); } mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the // song // length in // milliseconds // from URL // set song name TextView songName = (TextView) findViewById(R.id.songName); songName.setText(music.getTitle()); colorView.changeColorText(songName, user.getColor()); // set short text TextView shortText = (TextView) findViewById(R.id.shortText); shortText.setText(music.getShort_text()); TextView time_stamp = (TextView) findViewById(R.id.time_stamp); time_stamp.setText(music.getTime_stamp()); TextView total_like = (TextView) findViewById(R.id.total_like); total_like.setText(music.getTotal_like()); colorView.changeColorText(total_like, user.getColor()); TextView total_comment = (TextView) findViewById(R.id.total_comment); total_comment.setText(music.getTotal_comment()); colorView.changeColorText(total_comment, user.getColor()); ImageView likeImg = (ImageView) this.findViewById(R.id.likes_feed_txt); ImageView commentImg = (ImageView) this.findViewById(R.id.comments_feed_txt); colorView.changeColorLikeCommnent(likeImg, commentImg, user.getColor()); // set User image ImageView userImage = (ImageView) findViewById(R.id.image_user); networkUntil.drawImageUrl(userImage, music.getUser_image_path(), R.drawable.loading); userImage.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Intent intent = new Intent(MusicPlaySong.this, FriendTabsPager.class); intent.putExtra("user_id", music.getUser_id()); startActivity(intent); return false; } }); }
From source file:sg.fxl.topeka.widget.quiz.AudioQuizView.java
private void startPlaying() { player = new MediaPlayer(); try {/*w w w. j av a 2s .c om*/ player.setDataSource(fileName); player.prepare(); player.start(); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { setState(READY_RECORDED); startPlaying = !startPlaying; } }); } catch (IOException e) { Log.e(TAG, "prepare() failed"); } }