List of usage examples for android.media MediaPlayer setDataSource
public void setDataSource(MediaDataSource dataSource) throws IllegalArgumentException, IllegalStateException
From source file:hku.fyp14017.blencode.ui.controller.SoundController.java
public void startSound(SoundInfo soundInfo, MediaPlayer mediaPlayer) { if (!soundInfo.isPlaying) { try {//from w w w. ja va2 s .c o 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.eggwall.SoundSleep.AudioService.java
/** * Try getting music from the [sdcard]/music/sleeping * @return a valid media player if we can play from it. Returns null if we didn't find music, or we can't play * custom music for any reason./*from w w w . j av a2s . c o m*/ */ private MediaPlayer tryStartingMusic() { final MediaPlayer player = getGenericMediaPlayer(); // Try to open the SD card and read from there. If nothing is found, play the // default music. final int nextPosition = nextTrackFromCard(); if (nextPosition == INVALID_POSITION) { return null; } // Play files, not resources. Play the music file given here. final String file = mMusicDir.getAbsolutePath() + File.separator + mFilenames[nextPosition]; Log.d(TAG, "Now playing " + file); try { player.setDataSource(file); } catch (IOException e) { Log.e(TAG, "Could not create a media player instance. Full error below."); e.printStackTrace(); return null; } player.setOnCompletionListener(this); // Play this song, and a different one when done. player.setLooping(false); return player; }
From source file:brama.com.hearthum.waveform.WaveformFragment.java
protected void loadFromFile() { mFile = new File(mFilename); mLoadingLastUpdateTime = System.currentTimeMillis(); mLoadingKeepGoing = true;/*from w ww. ja v a 2s . c om*/ mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle(R.string.progress_dialog_loading); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener((DialogInterface dialog) -> mLoadingKeepGoing = false); mProgressDialog.show(); final CheapSoundFile.ProgressListener listener = (double fractionComplete) -> { long now = System.currentTimeMillis(); if (now - mLoadingLastUpdateTime > 100) { mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete)); mLoadingLastUpdateTime = now; } return mLoadingKeepGoing; }; // Create the MediaPlayer in a background thread new Thread() { public void run() { try { MediaPlayer player = new MediaPlayer(); player.setDataSource(mFile.getAbsolutePath()); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.prepare(); mPlayer = player; } catch (final java.io.IOException e) { Log.e(TAG, "Error while creating media player", e); } } }.start(); // Load the sound file in a background thread new Thread() { public void run() { try { mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener); } catch (final Exception e) { Log.e(TAG, "Error while loading sound file", e); mProgressDialog.dismiss(); mInfo.setText(e.toString()); return; } if (mLoadingKeepGoing) { mHandler.post(() -> finishOpeningSoundFile()); } } }.start(); }
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();// ww w . ja va2 s .c om 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:com.soubw.other.WaveformFragment.java
protected void loadFromFile() { mFile = new File(mFilename); mLoadingLastUpdateTime = System.currentTimeMillis(); mLoadingKeepGoing = true;/*from w w w . jav a 2 s.c o m*/ mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle(R.string.progress_dialog_loading); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mLoadingKeepGoing = false; } }); mProgressDialog.show(); final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() { @Override public boolean reportProgress(double fractionComplete) { long now = System.currentTimeMillis(); if (now - mLoadingLastUpdateTime > 100) { mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete)); mLoadingLastUpdateTime = now; } return mLoadingKeepGoing; } }; // Create the MediaPlayer in a background thread new Thread() { public void run() { try { MediaPlayer player = new MediaPlayer(); player.setDataSource(mFile.getAbsolutePath()); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.prepare(); mPlayer = player; } catch (final java.io.IOException e) { Log.e(TAG, "Error while creating media player", e); } } }.start(); // Load the sound file in a background thread new Thread() { public void run() { try { mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener); } catch (final Exception e) { Log.e(TAG, "Error while loading sound file", e); mProgressDialog.dismiss(); mInfo.setText(e.toString()); return; } if (mLoadingKeepGoing) { mHandler.post(new Runnable() { @Override public void run() { finishOpeningSoundFile(); } }); } } }.start(); }
From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java
public static boolean validateUrl(String url) { if (!URLUtil.isHttpUrl(url) && !URLUtil.isHttpsUrl(url)) { //if (LOCAL_LOGV) log("not a valid http or https url", "v"); return false; }//from w w w .ja v a 2s . co m //check for empty after prefix if (url.equals("http://") || url.equals("https://")) { return false; } MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(url); mediaPlayer.release(); } catch (IOException e) { return false; } return true; }
From source file:com.bayapps.android.robophish.playback.LocalPlayback.java
public boolean playNext(QueueItem item) { MediaPlayer nextPlayer; if (mMediaPlayer == mMediaPlayerA) { nextPlayer = mMediaPlayerB;/*from w ww.ja va 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:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java
private synchronized void doPlay(final DownloadFile downloadFile, int position, boolean start) { try {/*from w ww .j a v a 2s . c o m*/ final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile() : downloadFile.getPartialFile(); downloadFile.updateModificationDate(); mediaPlayer.setOnCompletionListener(null); mediaPlayer.reset(); setPlayerState(IDLE); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setDataSource(file.getPath()); setPlayerState(PREPARING); mediaPlayer.prepare(); setPlayerState(PREPARED); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { // Acquire a temporary wakelock, since when we return from // this callback the MediaPlayer will release its wakelock // and allow the device to go to sleep. wakeLock.acquire(60000); setPlayerState(COMPLETED); // If COMPLETED and not playing partial file, we are *really" finished // with the song and can move on to the next. if (!file.equals(downloadFile.getPartialFile())) { onSongCompleted(); return; } // If file is not completely downloaded, restart the playback from the current position. int pos = mediaPlayer.getCurrentPosition(); synchronized (DownloadServiceImpl.this) { // Work-around for apparent bug on certain phones: If close (less than ten seconds) to the end // of the song, skip to the next rather than restarting it. Integer duration = downloadFile.getSong().getDuration() == null ? null : downloadFile.getSong().getDuration() * 1000; if (duration != null) { if (Math.abs(duration - pos) < 10000) { LOG.info("Skipping restart from " + pos + " of " + duration); onSongCompleted(); return; } } LOG.info("Requesting restart from " + pos + " of " + duration); reset(); bufferTask = new BufferTask(downloadFile, pos); bufferTask.start(); } } }); if (position != 0) { LOG.info("Restarting player from position " + position); mediaPlayer.seekTo(position); } if (start) { mediaPlayer.start(); setPlayerState(STARTED); } else { setPlayerState(PAUSED); } lifecycleSupport.serializeDownloadQueue(); } catch (Exception x) { handleError(x); } }
From source file:it.iziozi.iziozi.gui.IOBoardActivity.java
public void tapOnSpeakableButton(final IOSpeakableImageButton spkBtn, final Integer level) { if (IOGlobalConfiguration.isEditing) { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); View layoutView = inflater.inflate(R.layout.editmode_alertview, null); builder.setTitle(getString(R.string.choose)); builder.setView(layoutView);/*www .j a v a 2 s .c o m*/ final AlertDialog dialog = builder.create(); final Switch matrioskaSwitch = (Switch) layoutView.findViewById(R.id.editModeAlertToggleBoard); Button editPictoButton = (Button) layoutView.findViewById(R.id.editModeAlertActionPicture); final Button editBoardButton = (Button) layoutView.findViewById(R.id.editModeAlertActionBoard); matrioskaSwitch.setChecked(spkBtn.getIsMatrioska()); editBoardButton.setEnabled(spkBtn.getIsMatrioska()); matrioskaSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { spkBtn.setIsMatrioska(isChecked); editBoardButton.setEnabled(isChecked); } }); editPictoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //spkBtn.showInsertDialog(); Intent cIntent = new Intent(getApplicationContext(), IOCreateButtonActivity.class); cIntent.putExtra(BUTTON_INDEX, mActualLevel.getBoardAtIndex(mActualIndex).getButtons().indexOf(spkBtn)); cIntent.putExtra(BUTTON_TEXT, spkBtn.getSentence()); cIntent.putExtra(BUTTON_TITLE, spkBtn.getmTitle()); cIntent.putExtra(BUTTON_IMAGE_FILE, spkBtn.getmImageFile()); cIntent.putExtra(BUTTON_AUDIO_FILE, spkBtn.getAudioFile()); startActivityForResult(cIntent, CREATE_BUTTON_CODE); matrioskaSwitch.setOnCheckedChangeListener(null); dialog.dismiss(); } }); editBoardButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IOLevel nestedBoard = spkBtn.getLevel(); pushLevel(nestedBoard); matrioskaSwitch.setOnCheckedChangeListener(null); dialog.dismiss(); } }); dialog.show(); } else { if (IOGlobalConfiguration.isScanMode) { IOSpeakableImageButton scannedButton = mActualLevel.getBoardAtIndex(mActualIndex).getButtons() .get(mActualScanIndex); if (scannedButton.getAudioFile() != null && scannedButton.getAudioFile().length() > 0) { final MediaPlayer mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(scannedButton.getAudioFile()); mPlayer.prepare(); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mPlayer.release(); } }); mPlayer.start(); } catch (IOException e) { Log.e("playback_debug", "prepare() failed"); } } else if (mCanSpeak) { Log.d("speakable_debug", "should say: " + scannedButton.getSentence()); if (scannedButton.getSentence() == "") tts.speak(getResources().getString(R.string.tts_nosentence), TextToSpeech.QUEUE_FLUSH, null); else tts.speak(scannedButton.getSentence(), TextToSpeech.QUEUE_FLUSH, null); } else { Toast.makeText(this, getResources().getString(R.string.tts_notinitialized), Toast.LENGTH_LONG) .show(); } if (scannedButton.getIsMatrioska() && null != scannedButton.getLevel()) { pushLevel(scannedButton.getLevel()); } } else { if (spkBtn.getAudioFile() != null && spkBtn.getAudioFile().length() > 0) { final MediaPlayer mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(spkBtn.getAudioFile()); mPlayer.prepare(); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mPlayer.release(); } }); mPlayer.start(); } catch (IOException e) { Log.e("playback_debug", "prepare() failed"); } } else if (mCanSpeak) { Log.d("speakable_debug", "should say: " + spkBtn.getSentence()); if (spkBtn.getSentence() == "") tts.speak(getResources().getString(R.string.tts_nosentence), TextToSpeech.QUEUE_FLUSH, null); else tts.speak(spkBtn.getSentence(), TextToSpeech.QUEUE_FLUSH, null); } else { Toast.makeText(this, getResources().getString(R.string.tts_notinitialized), Toast.LENGTH_LONG) .show(); } if (spkBtn.getIsMatrioska() && null != spkBtn.getLevel()) { pushLevel(spkBtn.getLevel()); } } } }
From source file:com.tsp.clipsy.audio.RingdroidEditActivity.java
private void loadFromFile() { mFile = new File(mFilename); mExtension = getExtensionFromFilename(mFilename); SongMetadataReader metadataReader = new SongMetadataReader(this, mFilename); mTitle = metadataReader.mTitle;/*from www. j av a 2 s. c o m*/ mArtist = metadataReader.mArtist; mAlbum = metadataReader.mAlbum; mYear = metadataReader.mYear; mGenre = metadataReader.mGenre; String titleLabel = mTitle; if (mArtist != null && mArtist.length() > 0) { titleLabel += " - " + mArtist; } setTitle(titleLabel); mLoadingStartTime = System.currentTimeMillis(); mLoadingLastUpdateTime = System.currentTimeMillis(); mLoadingKeepGoing = true; mProgressDialog = new ProgressDialog(RingdroidEditActivity.this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setTitle(R.string.progress_dialog_loading); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mLoadingKeepGoing = false; } }); mProgressDialog.show(); final CheapSoundFile.ProgressListener listener = new CheapSoundFile.ProgressListener() { public boolean reportProgress(double fractionComplete) { long now = System.currentTimeMillis(); if (now - mLoadingLastUpdateTime > 100) { mProgressDialog.setProgress((int) (mProgressDialog.getMax() * fractionComplete)); mLoadingLastUpdateTime = now; } return mLoadingKeepGoing; } }; // Create the MediaPlayer in a background thread mCanSeekAccurately = false; new Thread() { public void run() { mCanSeekAccurately = SeekTest.CanSeekAccurately(getPreferences(Context.MODE_PRIVATE)); System.out.println("Seek test done, creating media player."); try { MediaPlayer player = new MediaPlayer(); player.setDataSource(mFile.getAbsolutePath()); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.prepare(); mPlayer = player; } catch (final java.io.IOException e) { Runnable runnable = new Runnable() { public void run() { handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); } ; } }.start(); // Load the sound file in a background thread new Thread() { public void run() { try { mSoundFile = CheapSoundFile.create(mFile.getAbsolutePath(), listener); if (mSoundFile == null) { mProgressDialog.dismiss(); String name = mFile.getName().toLowerCase(); String[] components = name.split("\\."); String err; if (components.length < 2) { err = getResources().getString(R.string.no_extension_error); } else { err = getResources().getString(R.string.bad_extension_error) + " " + components[components.length - 1]; } final String finalErr = err; Runnable runnable = new Runnable() { public void run() { handleFatalError("UnsupportedExtension", finalErr, new Exception()); } }; mHandler.post(runnable); return; } } catch (final Exception e) { mProgressDialog.dismiss(); e.printStackTrace(); mInfo.setText(e.toString()); Runnable runnable = new Runnable() { public void run() { handleFatalError("ReadError", getResources().getText(R.string.read_error), e); } }; mHandler.post(runnable); return; } mProgressDialog.dismiss(); if (mLoadingKeepGoing) { Runnable runnable = new Runnable() { public void run() { finishOpeningSoundFile(); } }; mHandler.post(runnable); } else { RingdroidEditActivity.this.finish(); } } }.start(); }