List of usage examples for android.media MediaPlayer setOnCompletionListener
public void setOnCompletionListener(OnCompletionListener listener)
From source file:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java
private synchronized void doPlay(final DownloadFile downloadFile, int position, boolean start) { try {//from ww w . j a va 2s . c om 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);/*w ww.ja va 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:dk.bearware.gui.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String serverName = getIntent().getStringExtra(ServerEntry.KEY_SERVERNAME); if ((serverName != null) && !serverName.isEmpty()) setTitle(serverName);/*from ww w.j av a 2s . c o m*/ getActionBar().setDisplayHomeAsUpEnabled(true); restarting = (savedInstanceState != null); accessibilityAssistant = new AccessibilityAssistant(this); audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mediaButtonEventReceiver = new ComponentName(getPackageName(), MediaButtonEventReceiver.class.getName()); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)) .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakeLock.setReferenceCounted(false); channelsAdapter = new ChannelListAdapter(this.getBaseContext()); filesAdapter = new FileListAdapter(this, this, accessibilityAssistant); textmsgAdapter = new TextMessageAdapter(this.getBaseContext(), accessibilityAssistant); mediaAdapter = new MediaAdapter(this.getBaseContext()); // Create the adapter that will return a fragment for each of the five // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOnPageChangeListener(mSectionsPagerAdapter); setupButtons(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { final MediaPlayer mMediaPlayer; mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silence); mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { mMediaPlayer.release(); } }); mMediaPlayer.start(); } }
From source file:github.daneren2005.dsub.service.DownloadServiceImpl.java
private void setupHandlers(final DownloadFile downloadFile, final boolean isPartial) { final int duration = downloadFile.getSong().getDuration() == null ? 0 : downloadFile.getSong().getDuration() * 1000; mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { public boolean onError(MediaPlayer mediaPlayer, int what, int extra) { Log.w(TAG, "Error on playing file " + "(" + what + ", " + extra + "): " + downloadFile); int pos = cachedPosition; reset();/* ww w .j a va2 s .c o m*/ if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000))) { playNext(); } else { downloadFile.setPlaying(false); doPlay(downloadFile, pos, true); downloadFile.setPlaying(true); } return true; } }); 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); setPlayerStateCompleted(); int pos = cachedPosition; Log.i(TAG, "Ending position " + pos + " of " + duration); if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000))) { playNext(); return; } // If file is not completely downloaded, restart the playback from the current position. synchronized (DownloadServiceImpl.this) { if (downloadFile.isWorkDone()) { // Complete was called early even though file is fully buffered Log.i(TAG, "Requesting restart from " + pos + " of " + duration); reset(); downloadFile.setPlaying(false); doPlay(downloadFile, pos, true); downloadFile.setPlaying(true); } else { Log.i(TAG, "Requesting restart from " + pos + " of " + duration); reset(); bufferTask = new BufferTask(downloadFile, pos); bufferTask.start(); } } } }); }
From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java
protected void initializePlayer(MediaPlayer player) { if (LOCAL_LOGV) log("initializePlayer()", "v"); player.setOnPreparedListener(this); player.setOnInfoListener(this); player.setOnCompletionListener(this); player.setOnErrorListener(this); //player.setOnBufferingUpdateListener(this); return;/*w w w . j a v a 2s. c om*/ }
From source file:org.kontalk.ui.AbstractComposeFragment.java
@Override public void onUnbind(long messageId, AudioContentViewControl view) { AudioFragment audio = getAudioFragment(); if (audio != null && audio.getMessageId() == messageId) { mAudioControl = null;/*from w ww. j av a 2 s. co m*/ MediaPlayer player = audio.getPlayer(); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { AudioFragment audio = getAudioFragment(); if (audio != null) audio.seekPlayerTo(0); setAudioStatus(AudioContentView.STATUS_ENDED); } }); view.setProgressChangeListener(false); if (!MessagesProviderUtils.exists(getActivity(), messageId)) { resetAudio(view); } else { stopMediaPlayerUpdater(); } } }
From source file:mp.teardrop.PlaybackService.java
/** * Returns a new MediaPlayer object/*from w ww. j a v a 2s . c om*/ */ private MediaPlayer getNewMediaPlayer() { MediaPlayer mp = new MediaPlayer(); mp.setAudioStreamType(AudioManager.STREAM_MUSIC); mp.setOnCompletionListener(this); mp.setOnErrorListener(this); mp.setOnPreparedListener(this); return mp; }
From source file:org.botlibre.sdk.activity.ChatActivity.java
public MediaPlayer playAudio(String audio, boolean loop, boolean cache, boolean start) { try {//w w w. j av a 2s .c om Uri audioUri = null; if (cache) { audioUri = HttpGetVideoAction.fetchVideo(this, audio); } if (audioUri == null) { audioUri = Uri.parse(MainActivity.connection.fetchImage(audio).toURI().toString()); } final MediaPlayer audioPlayer = new MediaPlayer(); audioPlayer.setDataSource(getApplicationContext(), audioUri); audioPlayer.setOnErrorListener(new OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Log.wtf("Audio error", "what:" + what + " extra:" + extra); audioPlayer.stop(); audioPlayer.release(); return true; } }); audioPlayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { audioPlayer.release(); runOnUiThread(new Runnable() { public void run() { try { beginListening(); } catch (Exception e) { Log.e("ChatActivity", "MediaPlayer: " + e.getMessage()); } } }); } }); audioPlayer.prepare(); audioPlayer.setLooping(loop); if (start) { audioPlayer.start(); } return audioPlayer; } catch (Exception exception) { Log.wtf(exception.toString(), exception); return null; } }
From source file:org.moire.ultrasonic.service.DownloadServiceImpl.java
private void setupHandlers(final DownloadFile downloadFile, final boolean isPartial) { mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() { @Override//w w w . ja v a 2 s . c o m public boolean onError(MediaPlayer mediaPlayer, int what, int extra) { Log.w(TAG, String.format("Error on playing file (%d, %d): %s", what, extra, downloadFile)); int pos = cachedPosition; reset(); downloadFile.setPlaying(false); doPlay(downloadFile, pos, true); downloadFile.setPlaying(true); return true; } }); final int duration = downloadFile.getSong().getDuration() == null ? 0 : downloadFile.getSong().getDuration() * 1000; 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); int pos = cachedPosition; Log.i(TAG, String.format("Ending position %d of %d", pos, duration)); if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 1000))) { setPlayerStateCompleted(); if (Util.getGaplessPlaybackPreference(DownloadServiceImpl.this) && nextPlaying != null && nextPlayerState == PlayerState.PREPARED) { if (!nextSetup) { playNext(); } else { nextSetup = false; playNext(); } } else { onSongCompleted(); } return; } synchronized (DownloadServiceImpl.this) { if (downloadFile.isWorkDone()) { // Complete was called early even though file is fully buffered Log.i(TAG, String.format("Requesting restart from %d of %d", pos, duration)); reset(); downloadFile.setPlaying(false); doPlay(downloadFile, pos, true); downloadFile.setPlaying(true); } else { Log.i(TAG, String.format("Requesting restart from %d of %d", pos, duration)); reset(); bufferTask = new BufferTask(downloadFile, pos); bufferTask.start(); } } } }); }
From source file:org.kontalk.ui.AbstractComposeFragment.java
private boolean prepareAudio(File audioFile, final AudioContentViewControl view, final long messageId) { stopMediaPlayerUpdater();//from w w w . ja v a2s.c o m try { AudioFragment audio = getAudioFragment(); final MediaPlayer player = audio.getPlayer(); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.setDataSource(audioFile.getAbsolutePath()); player.prepare(); // prepare was successful audio.setMessageId(messageId); mAudioControl = view; view.prepare(player.getDuration()); player.seekTo(view.getPosition()); view.setProgressChangeListener(true); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { stopMediaPlayerUpdater(); view.end(); AudioFragment audio = getAudioFragment(); if (audio != null) { // this is mainly to get the wake lock released audio.pausePlaying(); audio.seekPlayerTo(0); } setAudioStatus(AudioContentView.STATUS_ENDED); } }); return true; } catch (IOException e) { Toast.makeText(getActivity(), R.string.err_file_not_found, Toast.LENGTH_SHORT).show(); return false; } }