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

The following examples show how to use android.media.MediaPlayer#prepareAsync() . 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: ws_Main3Activity.java    From styT with Apache License 2.0 6 votes vote down vote up
public void Bi(String object) {
    final MediaPlayer mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(object);
        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // 准备完成 开始播放
                mediaPlayer.start();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    //MediaPlayer mPlayer = MediaPlayer.create(this, object);
    // mPlayer.start();
}
 
Example 2
Source File: UserProfileActivity.java    From styT with Apache License 2.0 6 votes vote down vote up
public void Bi(String object) {
    final MediaPlayer mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(object);
        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // 准备完成 开始播放
                mediaPlayer.start();
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    //MediaPlayer mPlayer = MediaPlayer.create(this, object);
    // mPlayer.start();
}
 
Example 3
Source File: MediaPlayerActivity.java    From SendBird-Android with MIT License 6 votes vote down vote up
private void playVideo() {
    mProgressBar.setVisibility(View.VISIBLE);
    doCleanUp();
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(mUrl);
        mMediaPlayer.setDisplay(mSurfaceHolder);
        mMediaPlayer.prepareAsync();
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnVideoSizeChangedListener(this);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 4
Source File: CustomVideoView.java    From VideoOS-Android-SDK with GNU General Public License v3.0 6 votes vote down vote up
public void startPlay() {
        if (mSurfaceHolder == null) {
            return;
        }
        stopPlaying();
        // 关闭系统音乐声音
        try {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnPreparedListener(this);
            mIsPrepared = false;
            mMediaPlayer.setDisplay(mSurfaceHolder);
//            mMediaPlayer.setDataSource(mContext, Uri.parse("http://videojj-cdn.oss-cn-beijing.aliyuncs.com/flash/player/video/6.mp4"));
            mMediaPlayer.setDataSource(mContext, Uri.parse(mCurrentUrl));
//            mMediaPlayer.setDataSource(mContext, Uri.parse("https://static.videojj.com/online/video/Team%20Video%2B%2B_We_Are_Young.mp4"));
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.prepareAsync();
        } catch (Exception ex) {
            VenvyLog.e("media player error" + ex);
        }
    }
 
Example 5
Source File: CutSizeActivity.java    From WeiXinRecordedDemo with MIT License 6 votes vote down vote up
private void initMediaPlay(SurfaceTexture surface){

        try {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.setSurface(new Surface(surface));
            mMediaPlayer.setLooping(true);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                }
            });
            mMediaPlayer.prepareAsync();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
 
Example 6
Source File: VideoFileInputSource.java    From MockCamera with Apache License 2.0 6 votes vote down vote up
public void startPreview() {
    try {
        player = new MediaPlayer();
        AssetFileDescriptor afd = this.context.getAssets().openFd(this.filename);
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        player.setLooping(false);
        player.setOnCompletionListener(new VideoOnCompletionListener());
        player.setOnPreparedListener(this);
        player.prepareAsync();
        frameSize = new Size(this.player.getVideoWidth(), this.player.getVideoHeight());
        player.setSurface(new Surface(this.surfaceTexture));
        Log.d(TAG, "Video starting playback at: " + this.frameSize.width + "x" + this.frameSize.height);
    } catch (IOException e) {
        throw new RuntimeException("Could not open input video!", e);
    }
}
 
Example 7
Source File: LiveStuffH4.java    From goprohero with MIT License 6 votes vote down vote up
@Override
 public void surfaceCreated(SurfaceHolder sh) {
     _mediaPlayer = new MediaPlayer();
     _mediaPlayer.setDisplay(_surfaceHolder);

     Context context = getApplicationContext();
//     Map<String, String> headers = getRtspHeaders();
     Uri source = Uri.parse(RTSP_URL);

     try {
         // Specify the IP camera's URL and auth headers.
      //   _mediaPlayer.setDataSource(context, source, headers);

         // Begin the process of setting up a video stream.
         _mediaPlayer.setOnPreparedListener(this);
         _mediaPlayer.prepareAsync();
     }
     catch (Exception e) {}
 }
 
Example 8
Source File: EditVideoActivity.java    From WeiXinRecordedDemo with MIT License 6 votes vote down vote up
private void initMediaPlay(SurfaceTexture surface){

        try {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.setSurface(new Surface(surface));
            mMediaPlayer.setLooping(true);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayer.start();
                }
            });
            mMediaPlayer.prepareAsync();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
 
Example 9
Source File: OBAudioPlayer.java    From GLEXP-Team-onebillion with Apache License 2.0 6 votes vote down vote up
public void startPlayingAtTimeVolume(AssetFileDescriptor afd, long fr,float vol)
{
    if (isPlaying())
        stopPlaying();
    volume = vol;
    fromTime = fr;
    player = new MediaPlayer();
    player.setOnPreparedListener(this);
    player.setOnSeekCompleteListener(this);
    player.setOnCompletionListener(this);
    try
    {
        state = OBAP_PREPARING;
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        player.prepareAsync();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        setState(OBAP_IDLE);
        return;
    }

}
 
Example 10
Source File: JZMediaSystem.java    From JZVideoDemo with MIT License 5 votes vote down vote up
@Override
public void prepare() {
    try {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        if (dataSourceObjects.length > 1) {
            mediaPlayer.setLooping((boolean) dataSourceObjects[1]);
        }
        mediaPlayer.setOnPreparedListener(JZMediaSystem.this);
        mediaPlayer.setOnCompletionListener(JZMediaSystem.this);
        mediaPlayer.setOnBufferingUpdateListener(JZMediaSystem.this);
        mediaPlayer.setScreenOnWhilePlaying(true);
        mediaPlayer.setOnSeekCompleteListener(JZMediaSystem.this);
        mediaPlayer.setOnErrorListener(JZMediaSystem.this);
        mediaPlayer.setOnInfoListener(JZMediaSystem.this);
        mediaPlayer.setOnVideoSizeChangedListener(JZMediaSystem.this);
        mediaPlayer.setVolume(0f, 0f);
        Class<MediaPlayer> clazz = MediaPlayer.class;
        Method method = clazz.getDeclaredMethod("setDataSource", String.class, Map.class);
        if (dataSourceObjects.length > 2) {
            method.invoke(mediaPlayer, currentDataSource.toString(), dataSourceObjects[2]);
        } else {
            method.invoke(mediaPlayer, currentDataSource.toString(), null);
        }
        mediaPlayer.prepareAsync();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 11
Source File: VideoView.java    From Spectaculum with Apache License 2.0 5 votes vote down vote up
private void openVideo() {
    if (mUri == null || mInputSurfaceHolder == null) {
        // not ready for playback yet, will be called again later
        return;
    }

    release();

    try {
        mPlayer = new MediaPlayer();
        mPlayer.setSurface(getInputHolder().getSurface());
        mPlayer.setOnPreparedListener(mPreparedListener);
        mPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
        mPlayer.setOnCompletionListener(mCompletionListener);
        mPlayer.setOnErrorListener(mErrorListener);
        mPlayer.setOnInfoListener(mInfoListener);
        mPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mCurrentBufferPercentage = 0;
        mPlayer.setDataSource(getContext(), mUri, mHeaders);
        mCurrentState = STATE_PREPARING;
        mPlayer.prepareAsync();
    } catch (Exception e) {
        Log.e(TAG, "video open failed", e);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
    }
}
 
Example 12
Source File: OBVideoPlayer.java    From GLEXP-Team-onebillion with Apache License 2.0 5 votes vote down vote up
public void prepareForPlaying(AssetFileDescriptor afd, long atTime, OBUtils.RunLambda seekCompletion)
{
    if(afd == null || activityPaused )
        return;

    playAfterPrepare = false;
    condition = playerLock.newCondition();
    fromTime = atTime;

    if(seekCompletion != null)
        this.seekCompletionBlock = seekCompletion;

    player = new MediaPlayer();
    player.setSurface(surface);
    //surface.release();
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnSeekCompleteListener(this);
    player.setOnErrorListener(this);
    player.setOnVideoSizeChangedListener(this);

    try
    {
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        player.prepareAsync();

    }
    catch (Exception e)
    {
        e.printStackTrace();
        return;
    }
}
 
Example 13
Source File: OBVideoPlayer.java    From GLEXP-Team-onebillion with Apache License 2.0 5 votes vote down vote up
public void startPlayingAtTime(AssetFileDescriptor afd, long fr, MediaPlayer.OnPreparedListener preparedListener, MediaPlayer.OnCompletionListener completionListener)
{
    if(afd == null || activityPaused )
        return;

    condition = playerLock.newCondition();
    fromTime = fr;

    player = new MediaPlayer();
    player.setSurface(surface);
    //surface.release();
    player.setOnPreparedListener(preparedListener);
    player.setOnCompletionListener(completionListener);
    player.setOnSeekCompleteListener(this);
    player.setOnErrorListener(this);
    player.setOnVideoSizeChangedListener(this);
    try
    {
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        player.prepareAsync();

    }
    catch (Exception e)
    {
        e.printStackTrace();
        return;
    }
}
 
Example 14
Source File: MapboxSpeechPlayer.java    From graphhopper-navigation-android with MIT License 5 votes vote down vote up
private void setupMediaPlayer(String instructionPath) {
  if (TextUtils.isEmpty(instructionPath)) {
    return;
  }
  mediaPlayer = new MediaPlayer();
  setDataSource(instructionPath);
  mediaPlayer.prepareAsync();
  addListeners();
}
 
Example 15
Source File: MainActivity.java    From OpenLRC with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	
	// 歌曲路径
	String music = mDir + "1.mp3";
	// 歌词路径
	String lrc = mDir + "1.lrc";
	
	mLrc = (LrcView) findViewById(R.id.lrc);
	// 设置背景图片
	// 可以选择不设置
	// 最好是在真个屏幕设置该图片
	// 那样更好看
	mLrc.setBackground(BitmapFactory.decodeFile(mDir + "1.png"));
	
	mPlayer = new MediaPlayer();
	try {
		mPlayer.setDataSource(music);
		mPlayer.setOnPreparedListener(new PreparedListener());
		mPlayer.prepareAsync();
		
		// 设置lrc的路径
		mLrc.setLrcPath(lrc);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 16
Source File: VoIPBaseService.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
protected void startRingtoneAndVibration(int chatID){
	SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount);
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	boolean needRing=am.getRingerMode()!=AudioManager.RINGER_MODE_SILENT;
	/*if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
		try{
			int mode=Settings.Global.getInt(getContentResolver(), "zen_mode");
			if(needRing)
				needRing=mode==0;
		}catch(Exception ignore){}
	}*/
	if(needRing){
		if(!USE_CONNECTION_SERVICE){
			am.requestAudioFocus(this, AudioManager.STREAM_RING, AudioManager.AUDIOFOCUS_GAIN);
		}
		ringtonePlayer=new MediaPlayer();
		ringtonePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
			@Override
			public void onPrepared(MediaPlayer mediaPlayer){
				ringtonePlayer.start();
			}
		});
		ringtonePlayer.setLooping(true);
		ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING);
		try{
			String notificationUri;
			if(prefs.getBoolean("custom_"+chatID, false))
				notificationUri=prefs.getString("ringtone_path_"+chatID, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
			else
				notificationUri=prefs.getString("CallsRingtonePath", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
			ringtonePlayer.setDataSource(this, Uri.parse(notificationUri));
			ringtonePlayer.prepareAsync();
		}catch(Exception e){
			FileLog.e(e);
			if(ringtonePlayer!=null){
				ringtonePlayer.release();
				ringtonePlayer=null;
			}
		}
		int vibrate;
		if(prefs.getBoolean("custom_"+chatID, false))
			vibrate=prefs.getInt("calls_vibrate_"+chatID, 0);
		else
			vibrate=prefs.getInt("vibrate_calls", 0);
		if((vibrate!=2 && vibrate!=4 && (am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE || am.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)) ||
				(vibrate==4 && am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE)){
			vibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE);
			long duration=700;
			if(vibrate==1)
				duration/=2;
			else if(vibrate==3)
				duration*=2;
			vibrator.vibrate(new long[]{0, duration, 500}, 0);
		}
	}
}
 
Example 17
Source File: VoIPBaseService.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
protected void startRingtoneAndVibration(int chatID){
	SharedPreferences prefs = MessagesController.getNotificationsSettings(currentAccount);
	AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
	boolean needRing=am.getRingerMode()!=AudioManager.RINGER_MODE_SILENT;
	/*if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
		try{
			int mode=Settings.Global.getInt(getContentResolver(), "zen_mode");
			if(needRing)
				needRing=mode==0;
		}catch(Exception ignore){}
	}*/
	if(needRing){
		if(!USE_CONNECTION_SERVICE){
			am.requestAudioFocus(this, AudioManager.STREAM_RING, AudioManager.AUDIOFOCUS_GAIN);
		}
		ringtonePlayer=new MediaPlayer();
		ringtonePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
			@Override
			public void onPrepared(MediaPlayer mediaPlayer){
				ringtonePlayer.start();
			}
		});
		ringtonePlayer.setLooping(true);
		ringtonePlayer.setAudioStreamType(AudioManager.STREAM_RING);
		try{
			String notificationUri;
			if(prefs.getBoolean("custom_"+chatID, false))
				notificationUri=prefs.getString("ringtone_path_"+chatID, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
			else
				notificationUri=prefs.getString("CallsRingtonePath", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE).toString());
			ringtonePlayer.setDataSource(this, Uri.parse(notificationUri));
			ringtonePlayer.prepareAsync();
		}catch(Exception e){
			FileLog.e(e);
			if(ringtonePlayer!=null){
				ringtonePlayer.release();
				ringtonePlayer=null;
			}
		}
		int vibrate;
		if(prefs.getBoolean("custom_"+chatID, false))
			vibrate=prefs.getInt("calls_vibrate_"+chatID, 0);
		else
			vibrate=prefs.getInt("vibrate_calls", 0);
		if((vibrate!=2 && vibrate!=4 && (am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE || am.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)) ||
				(vibrate==4 && am.getRingerMode()==AudioManager.RINGER_MODE_VIBRATE)){
			vibrator=(Vibrator) getSystemService(VIBRATOR_SERVICE);
			long duration=700;
			if(vibrate==1)
				duration/=2;
			else if(vibrate==3)
				duration*=2;
			vibrator.vibrate(new long[]{0, duration, 500}, 0);
		}
	}
}
 
Example 18
Source File: UniversalVideoView.java    From LLApp with Apache License 2.0 4 votes vote down vote up
private void openVideo() {
    if (mUri == null || mSurfaceHolder == null) {
        // not ready for playback just yet, will try again later
        return;
    }
    AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
    am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // we shouldn't clear the target state, because somebody might have
    // called start() previously
    release(false);
    try {
        mMediaPlayer = new MediaPlayer();

        if (mAudioSession != 0) {
            mMediaPlayer.setAudioSessionId(mAudioSession);
        } else {
            mAudioSession = mMediaPlayer.getAudioSessionId();
        }
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mCurrentBufferPercentage = 0;
        mMediaPlayer.setDataSource(mContext, mUri);
        mMediaPlayer.setDisplay(mSurfaceHolder);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);
        mMediaPlayer.prepareAsync();


        // we don't set the target state here either, but preserve the
        // target state that was there before.
        mCurrentState = STATE_PREPARING;
        attachMediaController();
    } catch (IOException ex) {
        Log.w(TAG, "Unable to open content: " + mUri, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
    }
}
 
Example 19
Source File: AssetVideoView.java    From ResearchStack with Apache License 2.0 4 votes vote down vote up
private void openVideo() {
    if (mFileDescriptor == null || mSurfaceHolder == null) {
        // not ready for playback just yet, will try again later
        return;
    }
    // we shouldn't clear the target state, because somebody might have
    // called start() previously
    release(false);

    AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
    am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    try {
        mMediaPlayer = new MediaPlayer();

        if (mAudioSession != 0) {
            mMediaPlayer.setAudioSessionId(mAudioSession);
        } else {
            mAudioSession = mMediaPlayer.getAudioSessionId();
        }
        mMediaPlayer.setOnPreparedListener(mPreparedListener);
        mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
        mMediaPlayer.setOnCompletionListener(mCompletionListener);
        mMediaPlayer.setOnErrorListener(mErrorListener);
        mMediaPlayer.setOnInfoListener(mInfoListener);
        mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
        mCurrentBufferPercentage = 0;
        mMediaPlayer.setDataSource(mFileDescriptor, mStartOffset, mLength);
        mMediaPlayer.setDisplay(mSurfaceHolder);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setScreenOnWhilePlaying(true);
        mMediaPlayer.prepareAsync();


        // we don't set the target state here either, but preserve the
        // target state that was there before.
        mCurrentState = STATE_PREPARING;
        attachMediaController();
    } catch (IOException | IllegalArgumentException ex) {
        Log.w(TAG, "Unable to open content: " + mFileDescriptor, ex);
        mCurrentState = STATE_ERROR;
        mTargetState = STATE_ERROR;
        mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
        return;
    }
}
 
Example 20
Source File: FakeRingerActivity.java    From fake-call-lollipop with BSD 2-Clause "Simplified" License 3 votes vote down vote up
private void playVoice() {

        if (!voice.equals("")) {

            Uri voiceURI = Uri.parse(voice);

            voicePlayer = new MediaPlayer();

            try {
                voicePlayer.setDataSource(this, voiceURI);
            } catch (Exception e) {
                e.printStackTrace();
            }

            voicePlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);

            voicePlayer.prepareAsync();

            voicePlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });

        }

    }