Java Code Examples for android.media.MediaPlayer#prepare()

The following examples show how to use android.media.MediaPlayer#prepare() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PlayButton.java    From LoveTalkClient with Apache License 2.0 6 votes vote down vote up
public void playAudio() {
	if (prepared == false) {
		try {
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setDataSource(path);
			mediaPlayer.prepare();
			mediaPlayer.start();
			mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					setBackgroundResource(backResourceId);
				}
			});
			setBackgroundDrawable(null);
			prepared = true;
		} catch (IOException e) {
			e.printStackTrace();
			Utils.toast(e.getMessage());
		}
	} else {
		mediaPlayer.start();
		setBackgroundDrawable(null);
	}
}
 
Example 2
Source File: BeepManager.java    From ZXingProject with MIT License 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
	MediaPlayer mediaPlayer = new MediaPlayer();
	mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
	mediaPlayer.setOnCompletionListener(this);
	mediaPlayer.setOnErrorListener(this);
	try {
		AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
		try {
			mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
		} finally {
			file.close();
		}
		mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
		mediaPlayer.prepare();
		return mediaPlayer;
	} catch (IOException ioe) {
		Log.w(TAG, ioe);
		mediaPlayer.release();
		return null;
	}
}
 
Example 3
Source File: MenuGrid.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
        int position, long id) {
    MenuDisplayable value = (MenuDisplayable)parent.getAdapter().getItem(position);
    String audioURI = value.getAudioURI();
    MediaPlayer mp = new MediaPlayer();
    String audioFilename;
    if (audioURI != null && !audioURI.equals("")) {
        try {
            audioFilename = ReferenceManager.instance().DeriveReference(audioURI).getLocalURI();
            mp.setDataSource(audioFilename);
            mp.prepare();
            mp.start();
        } catch (IOException | IllegalStateException
                | InvalidReferenceException e) {
            e.printStackTrace();
        }
    }
    return false;
}
 
Example 4
Source File: RingtoneLoop.java    From ClockPlus with GNU General Public License v3.0 6 votes vote down vote up
public void play() {
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(mContext, mUri);
        if (mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
            // "Must call this method before prepare() or prepareAsync() in order
            // for the target stream type to become effective thereafter."
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mMediaPlayer.setLooping(true);
            // There is prepare() and prepareAsync().
            // "For files, it is OK to call prepare(), which blocks until
            // MediaPlayer is ready for playback."
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        }
    } catch (SecurityException | IOException e) {
        destroyLocalPlayer();
    }
}
 
Example 5
Source File: MainActivity.java    From pretixdroid with GNU General Public License v3.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    // mediaPlayer.setOnErrorListener(this);
    try {
        AssetFileDescriptor file = activity.getResources()
                .openRawResourceFd(R.raw.beep);
        try {
            mediaPlayer.setDataSource(file.getFileDescriptor(),
                    file.getStartOffset(), file.getLength());
        } finally {
            file.close();
        }
        mediaPlayer.setVolume(0.10f, 0.10f);
        mediaPlayer.prepare();
        return mediaPlayer;
    } catch (IOException ioe) {
        mediaPlayer.release();
        return null;
    }
}
 
Example 6
Source File: List_Activity.java    From Beginner-Level-Android-Studio-Apps with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
    MediaPlayer mp = new MediaPlayer();
    try
    {
        mp.setDataSource(list_files[i].getPath());
        mp.prepare();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    mp.start();

    Dialog_Fragment_Play dialog = new Dialog_Fragment_Play(this , list_files[i] , mp);
    dialog.show(this.getSupportFragmentManager() , "dialog");
}
 
Example 7
Source File: RecordDialog.java    From RecordDialog with MIT License 6 votes vote down vote up
private void startMediaPlayer() {
    mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(_AudioSavePathInDevice);
        mediaPlayer.prepare();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopMediaPlayer();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    _recordButton.setImageResource(R.drawable.ic_pause);
    STATE_BUTTON = "PLAY";
    playerSecondsElapsed = 0;
    startTimer();
    mediaPlayer.start();
}
 
Example 8
Source File: BeepManager.java    From barcodescanner-lib-aar with MIT License 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
  MediaPlayer mediaPlayer = new MediaPlayer();
  try {
    AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
    try {
      mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
    } finally {
      file.close();
    }
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setLooping(false);
    mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
    mediaPlayer.prepare();
    return mediaPlayer;
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    mediaPlayer.release();
    return null;
  }
}
 
Example 9
Source File: BeepManager.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
private MediaPlayer buildMediaPlayer(Context activity) {
  MediaPlayer mediaPlayer = new MediaPlayer();
  try {
    AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
    try {
      mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
    } finally {
      file.close();
    }
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setLooping(false);
    mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
    mediaPlayer.prepare();
    return mediaPlayer;
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    mediaPlayer.release();
    return null;
  }
}
 
Example 10
Source File: BeepManager.java    From reacteu-app with MIT License 6 votes vote down vote up
private static MediaPlayer buildMediaPlayer(Context activity) {
  MediaPlayer mediaPlayer = new MediaPlayer();
  mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  // When the beep has finished playing, rewind to queue up another one.
  mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer player) {
      player.seekTo(0);
    }
  });

  AssetFileDescriptor file = activity.getResources().openRawResourceFd(fakeR.getId("raw", "beep"));
  try {
    mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
    file.close();
    mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
    mediaPlayer.prepare();
  } catch (IOException ioe) {
    Log.w(TAG, ioe);
    mediaPlayer = null;
  }
  return mediaPlayer;
}
 
Example 11
Source File: AudioRecordingActivity.java    From coursera-android with MIT License 6 votes vote down vote up
private void startPlaying() {

        mPlayer = new MediaPlayer();

        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mPlayButton.performClick();
                mPlayButton.setChecked(false);
            }
        });

        try {
            mPlayer.setDataSource(mFileName);
            mPlayer.prepare();
            mPlayer.start();
        } catch (IOException e) {
            Log.e(TAG, "Couldn't prepare and start MediaPlayer");
        }

    }
 
Example 12
Source File: AlarmRingService.java    From Moring-Alarm with Apache License 2.0 6 votes vote down vote up
private void ringTheAlarm(String song) {
    AssetFileDescriptor assetFileDescriptor= null;
    try {
        mPlayer=new MediaPlayer();

        mPlayer.reset();
        mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        if(song.contains("/")){
            //说明是自定义铃声
            mPlayer.setDataSource(song);
        }else{
            assetFileDescriptor = this.getAssets().openFd(song);
            mPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
                    assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
        }
        mPlayer.setVolume(1f, 1f);
        mPlayer.setLooping(true);
        mPlayer.prepare();
        mPlayer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 13
Source File: AppController.java    From android-docs-samples with Apache License 2.0 6 votes vote down vote up
public static void playAudio(byte[] byteArray) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    try {
        File tempFile = File.createTempFile("dialogFlow", null,
                Environment.getExternalStorageDirectory());
        tempFile.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tempFile);
        fos.write(byteArray);
        fos.close();
        mediaPlayer.reset();
        FileInputStream fis = new FileInputStream(tempFile);
        mediaPlayer.setDataSource(fis.getFD());

        mediaPlayer.prepare();
        mediaPlayer.start();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
 
Example 14
Source File: PlaybackFragment.java    From Android-AudioRecorder-App with Apache License 2.0 6 votes vote down vote up
private void startPlaying() {
  mPlayButton.setImageResource(R.drawable.ic_media_pause);
  mMediaPlayer = new MediaPlayer();

  try {
    mMediaPlayer.setDataSource(item.getFilePath());
    mMediaPlayer.prepare();
    mSeekBar.setMax(mMediaPlayer.getDuration());

    mMediaPlayer.setOnPreparedListener(mp -> mMediaPlayer.start());
  } catch (IOException e) {
    Log.e(LOG_TAG, "prepare() failed");
  }

  mMediaPlayer.setOnCompletionListener(mp -> stopPlaying());

  updateSeekBar();

  //keep screen on while playing audio
  getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
 
Example 15
Source File: Cocos2dxMusic.java    From Example-of-Cocos2DX with MIT License 6 votes vote down vote up
/**
 * create mediaplayer for music
 * 
 * @param pPath
 *            the pPath relative to assets
 * @return
 */
private MediaPlayer createMediaplayer(final String pPath) {
	MediaPlayer mediaPlayer = new MediaPlayer();

	try {
		if (pPath.startsWith("/")) {
			final FileInputStream fis = new FileInputStream(pPath);
			mediaPlayer.setDataSource(fis.getFD());
			fis.close();
		} else {
			final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(pPath);
			mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
		}

		mediaPlayer.prepare();

		mediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
	} catch (final Exception e) {
		mediaPlayer = null;
		Log.e(Cocos2dxMusic.TAG, "error: " + e.getMessage(), e);
	}

	return mediaPlayer;
}
 
Example 16
Source File: SoundLogic.java    From redalert-android with Apache License 2.0 5 votes vote down vote up
static void playSoundURI(Uri alarmSoundUi, Context context) {
    // No URI?
    if (alarmSoundUi == null) {
        return;
    }

    // Already initialized or currently playing?
    stopSound(context);

    // Create new MediaPlayer
    mPlayer = new MediaPlayer();

    // Wake up processor
    mPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);

    // Set stream type
    mPlayer.setAudioStreamType(getSoundStreamType(context));

    try {
        // Set URI data source
        mPlayer.setDataSource(context, alarmSoundUi);

        // Prepare media player
        mPlayer.prepare();
    }
    catch (Exception exc) {
        // Log it
        Log.e(Logging.TAG, "Media player preparation failed", exc);

        // Show visible error toast
        Toast.makeText(context, exc.toString(), Toast.LENGTH_LONG).show();
    }

    // Actually start playing
    mPlayer.start();
}
 
Example 17
Source File: LocationAwareService.java    From LocationAware with Apache License 2.0 5 votes vote down vote up
private void startPlayer() {
  mPlayer = new MediaPlayer();
  mPlayer.setOnErrorListener(mErrorListener);

  try {
    isAlarmRinging = true;
    // add vibration to alarm alert if it is set
    //if (App.getState().settings().vibrate()) {
    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    mHandler.post(mVibrationRunnable);
    //}
    // Player setup is here
    String ringtone;// = App.getState().settings().ringtone();
    //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    //    && ringtone.startsWith("content://media/external/")
    //    && checkSelfPermission(
    //    Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
    ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
    //}
    mPlayer.setDataSource(this, Uri.parse(ringtone));
    mPlayer.setLooping(true);
    mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
    mPlayer.setVolume(mVolumeLevel, mVolumeLevel);
    mPlayer.prepare();
    mPlayer.start();

    //if (App.getState().settings().ramping()) {
    //  mHandler.postDelayed(mVolumeRunnable, VOLUME_INCREASE_DELAY);
    //} else {
    mPlayer.setVolume(MAX_VOLUME, MAX_VOLUME);
    //}
  } catch (Exception e) {
    isAlarmRinging = false;
    if (mPlayer.isPlaying()) {
      mPlayer.stop();
    }
    stopSelf();
  }
}
 
Example 18
Source File: MainActivity.java    From MultiMediaSample with Apache License 2.0 5 votes vote down vote up
/**
 * 播放输入框的文件
 */
private void play(){
    String path=etPath.getText().toString().trim();
    mMediapPlayer=new MediaPlayer();
    try {
        //设置数据类型
        mMediapPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        //设置以下播放器显示的位置
        mMediapPlayer.setDisplay(holder);

        mMediapPlayer.setDataSource(path);
        mMediapPlayer.prepare();
        mMediapPlayer.start();

        mMediapPlayer .setOnCompletionListener(this);
        //把当前播放器的状诚置为:播放中
        currentstate=PLAYING;

        //把音乐文件的总长度取出来,设置给seekbar作为最大值
        int duration=mMediapPlayer.getDuration();//总时长
        mSeekbar.setMax(duration);
        //把总时间显示textView上
        int m=duration/1000/60;
        int s=duration/1000%60;
        tvTotalTime.setText("/"+m+":"+s);
        tvCurrentTime.setText("00:00");

        isStopUpdatingProgress=false;
        new Thread(new UpdateProgressRunnable()).start();


    }catch(Exception e) {
        e.printStackTrace();
    }
}
 
Example 19
Source File: MultiPlayer.java    From VinylMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param player The {@link MediaPlayer} to use
 * @param path   The path of the file, or the http/rtsp URL of the stream
 *               you want to play
 * @return True if the <code>player</code> has been prepared and is
 * ready to play, false otherwise
 */
private boolean setDataSourceImpl(@NonNull final MediaPlayer player, @NonNull final String path) {
    if (context == null) {
        return false;
    }
    try {
        player.reset();
        player.setOnPreparedListener(null);
        if (path.startsWith("content://")) {
            player.setDataSource(context, Uri.parse(path));
        } else {
            player.setDataSource(path);
        }
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.prepare();
    } catch (Exception e) {
        return false;
    }
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);
    final Intent intent = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
    intent.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
    intent.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, context.getPackageName());
    intent.putExtra(AudioEffect.EXTRA_CONTENT_TYPE, AudioEffect.CONTENT_TYPE_MUSIC);
    context.sendBroadcast(intent);
    return true;
}
 
Example 20
Source File: MediaPlayerDemo_Video.java    From codeexamples-android with Eclipse Public License 1.0 4 votes vote down vote up
private void playVideo(Integer Media) {
    doCleanUp();
    try {

        switch (Media) {
            case LOCAL_VIDEO:
                /*
                 * TODO: Set the path variable to a local media file path.
                 */
                path = "";
                if (path == "") {
                    // Tell the user to provide a media file URL.
                    Toast
                            .makeText(
                                    MediaPlayerDemo_Video.this,
                                    "Please edit MediaPlayerDemo_Video Activity, "
                                            + "and set the path variable to your media file path."
                                            + " Your media file must be stored on sdcard.",
                                    Toast.LENGTH_LONG).show();

                }
                break;
            case STREAM_VIDEO:
                /*
                 * TODO: Set path variable to progressive streamable mp4 or
                 * 3gpp format URL. Http protocol should be used.
                 * Mediaplayer can only play "progressive streamable
                 * contents" which basically means: 1. the movie atom has to
                 * precede all the media data atoms. 2. The clip has to be
                 * reasonably interleaved.
                 * 
                 */
                path = "";
                if (path == "") {
                    // Tell the user to provide a media file URL.
                    Toast
                            .makeText(
                                    MediaPlayerDemo_Video.this,
                                    "Please edit MediaPlayerDemo_Video Activity,"
                                            + " and set the path variable to your media file URL.",
                                    Toast.LENGTH_LONG).show();

                }

                break;


        }

        // Create a new media player and set the listeners
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(path);
        mMediaPlayer.setDisplay(holder);
        mMediaPlayer.prepare();
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnVideoSizeChangedListener(this);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);


    } catch (Exception e) {
        Log.e(TAG, "error: " + e.getMessage(), e);
    }
}