Example usage for android.media MediaPlayer prepare

List of usage examples for android.media MediaPlayer prepare

Introduction

In this page you can find the example usage for android.media MediaPlayer prepare.

Prototype

public void prepare() throws IOException, IllegalStateException 

Source Link

Document

Prepares the player for playback, synchronously.

Usage

From source file:org.catrobat.catroid.ui.controller.SoundController.java

private void handleSoundInfo(SoundViewHolder holder, SoundInfo soundInfo, SoundBaseAdapter soundAdapter,
        int position, Context context) {
    try {//from w w  w. j  av a2s  .  co 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(R.drawable.ic_media_stop);
            holder.playAndStopButton.setContentDescription(context.getString(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(R.drawable.ic_media_play);
            holder.playAndStopButton.setContentDescription(context.getString(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:hku.fyp14017.blencode.ui.controller.SoundController.java

public void startSound(SoundInfo soundInfo, MediaPlayer mediaPlayer) {
    if (!soundInfo.isPlaying) {
        try {// ww  w . j  ava  2s  . c  om
            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:it.interfree.leonardoce.bootreceiver.AlarmKlaxon.java

private void startAlarm(MediaPlayer player)
        throws java.io.IOException, IllegalArgumentException, IllegalStateException {
    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Non deve suonare se il cellulare e' silenzioso
    Log.v(LTAG, "Stato del telefono: " + audioManager.getRingerMode());

    // do not play alarms if stream volume is 0
    // (typically because ringer mode is silent).
    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0
            && audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT
            && audioManager.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE) {
        player.setAudioStreamType(AudioManager.STREAM_ALARM);
        player.setLooping(true);/*  w w w.  j av  a2  s.  co  m*/
        player.prepare();
        player.start();
    }
}

From source file:brama.com.hearthum.waveform.WaveformFragment.java

protected void loadFromFile() {
    mFile = new File(mFilename);
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;/*w  ww  . j a  v  a 2  s .  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:com.soubw.other.WaveformFragment.java

protected void loadFromFile() {
    mFile = new File(mFilename);
    mLoadingLastUpdateTime = System.currentTimeMillis();
    mLoadingKeepGoing = true;//from  www .java  2  s .c om
    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:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java

private synchronized void doPlay(final DownloadFile downloadFile, int position, boolean start) {
    try {/*from   www .  j  a va 2 s. co 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:com.hhunj.hhudata.ForegroundService.java

private MediaPlayer ring() throws Exception, IOException {

    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    MediaPlayer player = new MediaPlayer();

    player.setDataSource(this, alert);

    final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {

        player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

        player.setLooping(true);//w w w . ja v a  2s .c o m

        player.prepare();

        player.start();

    }

    return player;

}

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);/*from   ww w  .  ja va2  s . co  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.massivcode.androidmusicplayer.services.MusicService.java

private void setNextMusicInfo(MediaPlayer mp, boolean isShuffle, boolean isRepeat) throws IOException {

    if (isShuffle) {
        mCurrentPosition = shuffle(mCurrentPlaylist.size());
    } else {//w ww . j  ava2 s .  c o m
        if (mCurrentPosition < getCurrentPlaylistSize()) {
            mCurrentPosition++;
        } else {
            mCurrentPosition = 0;
        }
    }

    mp.setDataSource(getApplicationContext(), switchIdToUri(mCurrentPlaylist.get(mCurrentPosition)));
    mCurrentMusicInfo = MusicInfoLoadUtil.getSelectedMusicInfo(getApplicationContext(),
            mCurrentPlaylist.get(mCurrentPosition));

    if (isShuffle) {
        mp.prepare();
        mp.start();
        isReady = true;
    } else {
        if (isRepeat) {
            mp.prepare();
            mp.start();
            isReady = true;
        } else {
            if (mCurrentPosition != 0) {
                mp.prepare();
                mp.start();
                isReady = true;
            } else {
                mp.stop();
                mp.reset();
                isReady = false;
            }
        }
    }
}

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;/* w w  w .j ava 2  s  . c  om*/
    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();
}