List of usage examples for android.media MediaPlayer prepare
public void prepare() throws IOException, IllegalStateException
From source file:org.cyanogenmod.theme.chooser.AudiblePreviewFragment.java
private MediaPlayer initAudibleMediaPlayer(AssetFileDescriptor afd, int type) throws IOException { MediaPlayer mp = mMediaPlayers.get(type); if (mp == null) { mp = new MediaPlayer(); mMediaPlayers.put(type, mp);/*from w ww . j a va 2 s . c o m*/ } else { mp.reset(); } mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); mp.prepare(); mp.setOnCompletionListener(mPlayCompletionListener); return mp; }
From source file:com.polyvi.xface.extension.capture.MediaType.java
/** * audio video ./* w w w. j a v a2 s.c o m*/ * * @param fileAbsPath ? * @param obj ? * @param isVideo ? video * @return ? JSONObject * @throws JSONException */ private JSONObject getAudioVideoData(String fileAbsPath, JSONObject obj, boolean isVideo) throws JSONException { MediaPlayer player = new MediaPlayer(); try { player.setDataSource(fileAbsPath); player.prepare(); obj.put(PROP_DURATION, player.getDuration() / XConstant.MILLISECONDS_PER_SECOND); if (isVideo) { obj.put(PROP_HEIGHT, player.getVideoHeight()); obj.put(PROP_WIDTH, player.getVideoWidth()); } } catch (IOException e) { XLog.e(CLASS_NAME, "Error: loading video file"); } player.release(); return obj; }
From source file:org.FrancoisDescamps.CatPlayer.MusicService.java
public void playMusic(final String pathToMusic) { //register receiver IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); HeadphonesUnplugReceiver receiver = new HeadphonesUnplugReceiver(); registerReceiver(receiver, receiverFilter); if (mp != null) { mp.stop();/*from w ww.j a va 2 s . c o m*/ mp = null; } try { mp = new MediaPlayer(); mp.setAudioStreamType(AudioManager.STREAM_MUSIC); mp.setDataSource(pathToMusic); mp.prepare(); mp.start(); } catch (Exception e) { /*NOP*/ } mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { switch (repeat) { case 0: // Lecture en boucle dsactive /* NOP */ break; case 1: // Lecture en boucle d'une seule musique playMusic(pathToMusic); break; case 2: // Lecture en boucle de toutes les musiques if (positionOfInitialMusic + cpt + 1 == queu.size()) { cpt = 0; positionOfInitialMusic = 0; } else { cpt++; } playMusic(queu.get(positionOfInitialMusic + cpt).getPath()); break; } currentTitle = properties[0][positionOfInitialMusic + cpt]; currentAlbum = properties[1][positionOfInitialMusic + cpt]; currentArtist = properties[2][positionOfInitialMusic + cpt]; currentPath = properties[3][positionOfInitialMusic + cpt]; musicAsChanged = true; MainActivity.notifyOtherMusicStarted(); buildNotification(true); //save "cpt" editor = preferences.edit(); editor.putInt("cpt", cpt); if (Build.VERSION.SDK_INT < 9) { editor.commit(); } else { editor.apply(); } } }); }
From source file:org.kontalk.ui.AudioDialog.java
void playAudio() { mProgressBar.setClickable(true);/*from www .ja v a2s. c om*/ try { MediaPlayer player = mData.getPlayer(); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.setDataSource(mFile.getAbsolutePath()); player.prepare(); } catch (IOException e) { Log.e(TAG, "error reading from external storage", e); new MaterialDialog.Builder(getContext()).content(R.string.err_playing_sdcard) .positiveText(android.R.string.ok).show(); } catch (Exception e) { Log.e(TAG, "error playing audio", e); } setupForPlaying(); animate(mProgressBar, null, 0, MAX_PROGRESS, mData.getPlayer().getDuration()); resumeAudio(); }
From source file:com.karura.framework.plugins.Capture.java
/** * Get the Image specific attributes//from w w w.jav a 2s.co 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 getAudioVideoMetadata(String filePath, JSONObject obj, boolean video) throws JSONException { MediaPlayer player = new MediaPlayer(); try { player.setDataSource(filePath); player.prepare(); obj.put(DURATION_FIELD, player.getDuration()); if (video) { obj.put(HEIGHT_FIELD, player.getVideoHeight()); obj.put(WIDTH_FIELD, player.getVideoWidth()); } } catch (IOException e) { Log.d(LOG_TAG, "Error: loading video file"); } return obj; }
From source file:org.yuttadhammo.BodhiTimer.TimerReceiver.java
@Override public void onReceive(Context context, Intent pintent) { Log.v(TAG, "ALARM: received alarm"); NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (player != null) { Log.v(TAG, "Releasing media player..."); try {/*w w w . ja v a 2s .com*/ player.release(); player = null; } catch (Exception e) { e.printStackTrace(); player = null; } finally { // do nothing } } // Cancel notification and return... if (CANCEL_NOTIFICATION.equals(pintent.getAction())) { Log.v(TAG, "Cancelling notification..."); mNM.cancelAll(); return; } // ...or display a new one Log.v(TAG, "Showing notification..."); player = new MediaPlayer(); int setTime = pintent.getIntExtra("SetTime", 0); String setTimeStr = TimerUtils.time2humanStr(context, setTime); Log.v(TAG, "Time: " + setTime); CharSequence text = context.getText(R.string.Notification); CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr); // Load the settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean led = prefs.getBoolean("LED", true); boolean vibrate = prefs.getBoolean("Vibrate", true); String notificationUri = ""; boolean useAdvTime = prefs.getBoolean("useAdvTime", false); String advTimeString = prefs.getString("advTimeString", ""); String[] advTime = null; int advTimeIndex = 1; if (useAdvTime && advTimeString.length() > 0) { advTime = advTimeString.split("\\^"); advTimeIndex = prefs.getInt("advTimeIndex", 1); String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound if (thisAdvTime.length == 3) notificationUri = thisAdvTime[1]; if (notificationUri.equals("sys_def")) notificationUri = prefs.getString("NotificationUri", "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell); } else notificationUri = prefs.getString("NotificationUri", "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell); Log.v(TAG, "notification uri: " + notificationUri); if (notificationUri.equals("system")) notificationUri = prefs.getString("SystemUri", ""); else if (notificationUri.equals("file")) notificationUri = prefs.getString("FileUri", ""); else if (notificationUri.equals("tts")) { notificationUri = ""; final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done)); Intent ttsIntent = new Intent(context, TTSService.class); ttsIntent.putExtra("spoken_text", ttsString); context.startService(ttsIntent); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext()) .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest); Uri uri = null; // Play a sound! if (!notificationUri.equals("")) uri = Uri.parse(notificationUri); // Vibrate if (vibrate && uri == null) { mBuilder.setDefaults(Notification.DEFAULT_VIBRATE); } // Have a light if (led) { mBuilder.setLights(0xff00ff00, 300, 1000); } mBuilder.setAutoCancel(true); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(context, TimerActivity.class); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(TimerActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); // Create intent for cancelling the notification Context appContext = context.getApplicationContext(); Intent intent = new Intent(appContext, TimerReceiver.class); intent.setAction(CANCEL_NOTIFICATION); // Cancel the pending cancellation and create a new one PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); if (uri != null) { //remove notification sound mBuilder.setSound(null); try { if (player != null && player.isPlaying()) { player.release(); player = new MediaPlayer(); } int currVolume = prefs.getInt("tone_volume", 0); if (currVolume != 0) { float log1 = (float) (Math.log(100 - currVolume) / Math.log(100)); player.setVolume(1 - log1, 1 - log1); } player.setDataSource(context, uri); player.prepare(); player.setLooping(false); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); player.start(); if (vibrate) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(1000); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (prefs.getBoolean("AutoClear", false)) { // Determine duration of notification sound int duration = 5000; if (uri != null) { MediaPlayer cancelPlayer = new MediaPlayer(); try { cancelPlayer.setDataSource(context, uri); cancelPlayer.prepare(); duration = Math.max(duration, cancelPlayer.getDuration() + 2000); } catch (java.io.IOException ex) { Log.e(TAG, "Cannot get sound duration: " + ex); duration = 30000; // on error, default to 30 seconds } finally { cancelPlayer.release(); } cancelPlayer.release(); } Log.v(TAG, "Notification duration: " + duration + " ms"); // Schedule cancellation AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration, pendingCancelIntent); } if (useAdvTime && advTimeString.length() > 0) { Intent broadcast = new Intent(); SharedPreferences.Editor editor = prefs.edit(); if (advTimeIndex < advTime.length) { editor.putInt("advTimeIndex", advTimeIndex + 1); String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound int time = Integer.parseInt(thisAdvTime[0]); broadcast.putExtra("time", time); // Save new time editor.putLong("TimeStamp", new Date().getTime() + time); editor.putInt("LastTime", time); // editor.putString("NotificationUri", thisAdvTime[1]); mNM.cancelAll(); Log.v(TAG, "Starting next iteration of the timer service ..."); Intent rintent = new Intent(context, TimerReceiver.class); rintent.putExtra("SetTime", time); PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent); } else { broadcast.putExtra("stop", true); editor.putInt("advTimeIndex", 1); } broadcast.setAction(BROADCAST_RESET); context.sendBroadcast(broadcast); editor.apply(); } else if (prefs.getBoolean("AutoRestart", false)) { int time = pintent.getIntExtra("SetTime", 0); if (time != 0) { mNM.cancel(0); Log.v(TAG, "Restarting the timer service ..."); Intent rintent = new Intent(context, TimerReceiver.class); rintent.putExtra("SetTime", time); PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent); // Save new time SharedPreferences.Editor editor = prefs.edit(); editor.putLong("TimeStamp", new Date().getTime() + time); editor.putInt("LastTime", time); editor.apply(); Intent broadcast = new Intent(); broadcast.putExtra("time", time); broadcast.setAction(BROADCAST_RESET); context.sendBroadcast(broadcast); } } mNotificationManager.notify(0, mBuilder.build()); Log.d(TAG, "ALARM: alarm finished"); }
From source file:org.cocos2dx.lib.Cocos2dxMusic.java
/** * create mediaplayer for music/* w w w. j a va 2s.c om*/ * @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; }
From source file:com.mattprecious.prioritysms.receiver.AlarmReceiver.java
private void doNotify(Context context, BaseProfile profile) { AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); MediaPlayer mediaPlayer = new MediaPlayer(); try {/*from w w w. j a va 2s . c o m*/ if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL || profile.isOverrideSilent()) { mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK); mediaPlayer.setAudioStreamType( profile.isOverrideSilent() ? AudioManager.STREAM_ALARM : AudioManager.STREAM_NOTIFICATION); mediaPlayer.setDataSource(context, profile.getRingtone()); mediaPlayer.prepare(); mediaPlayer.start(); if (profile.isVibrate()) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(VIBRATE_PATTERN, -1); } } } catch (IllegalArgumentException e) { Log.e(TAG, "failed to play audio", e); } catch (IOException e) { Log.e(TAG, "failed to play audio", e); } }
From source file:hku.fyp14017.blencode.ui.controller.SoundController.java
private void handleSoundInfo(SoundViewHolder holder, SoundInfo soundInfo, SoundBaseAdapter soundAdapter, int position, Context context) { try {//from w w w .jav a 2s .c o m MediaPlayer tempPlayer = new MediaPlayer(); tempPlayer.setDataSource(soundInfo.getAbsolutePath()); tempPlayer.prepare(); long milliseconds = tempPlayer.getDuration(); long seconds = milliseconds / 1000; if (seconds == 0) { seconds = 1; } String timeDisplayed = DateUtils.formatElapsedTime(seconds); holder.timePlayedChronometer.setText(timeDisplayed); holder.timePlayedChronometer.setVisibility(Chronometer.VISIBLE); if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) { SoundBaseAdapter.setElapsedMilliSeconds(0); } else { SoundBaseAdapter.setElapsedMilliSeconds( SystemClock.elapsedRealtime() - SoundBaseAdapter.getCurrentPlayingBase()); } if (soundInfo.isPlaying) { holder.playAndStopButton.setImageResource(hku.fyp14017.blencode.R.drawable.ic_media_stop); holder.playAndStopButton .setContentDescription(context.getString(hku.fyp14017.blencode.R.string.sound_stop)); if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) { startPlayingSound(holder.timePlayedChronometer, position, soundAdapter); } else if ((position == soundAdapter.getCurrentPlayingPosition()) && (SoundBaseAdapter.getElapsedMilliSeconds() > (milliseconds - 1000))) { stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter); } else { continuePlayingSound(holder.timePlayedChronometer, SystemClock.elapsedRealtime()); } } else { holder.playAndStopButton.setImageResource(hku.fyp14017.blencode.R.drawable.ic_media_play); holder.playAndStopButton .setContentDescription(context.getString(hku.fyp14017.blencode.R.string.sound_play)); stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter); } tempPlayer.reset(); tempPlayer.release(); } catch (IOException ioException) { Log.e(TAG, "Cannot get view.", ioException); } }
From source file:org.schabi.terminightor.NightKillerService.java
private MediaPlayer setupNewMediaPlayer(Alarm alarm) { MediaPlayer mediaPlayer = null; try {//from ww w . j av a 2 s. co m mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(this, Uri.parse(alarm.getAlarmTone())); boolean overrideVolume = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(getString(R.string.overrideAlarmVolume), false); if (overrideVolume) { mediaPlayer.setVolume(1.0f, 1.0f); } mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mediaPlayer.setLooping(true); mediaPlayer.prepare(); } catch (Exception e) { e.printStackTrace(); } return mediaPlayer; }