Java Code Examples for android.media.MediaPlayer

The following examples show how to use android.media.MediaPlayer. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: AntennaPod-AudioPlayer   Source File: AndroidAudioPlayer.java    License: Apache License 2.0 6 votes vote down vote up
public void onPrepared(MediaPlayer mp) {
    Log.d(AMP_TAG, "Calling onPreparedListener.onPrepared()");
    if (AndroidAudioPlayer.this.owningMediaPlayer != null) {
        AndroidAudioPlayer.this.lockMuteOnPreparedCount.lock();
        try {
            if (AndroidAudioPlayer.this.muteOnPreparedCount > 0) {
                AndroidAudioPlayer.this.muteOnPreparedCount--;
            } else {
                AndroidAudioPlayer.this.muteOnPreparedCount = 0;
                Log.d(AMP_TAG, "Invoking AndroidMediaPlayer.this.owningMediaPlayer.onPreparedListener.onPrepared");
                AndroidAudioPlayer.this.owningMediaPlayer.onPreparedListener.onPrepared(AndroidAudioPlayer.this.owningMediaPlayer);
            }
        } finally {
            AndroidAudioPlayer.this.lockMuteOnPreparedCount.unlock();
        }
        if (owningMediaPlayer.mpi != AndroidAudioPlayer.this) {
            Log.d(AMP_TAG, "owningMediaPlayer has changed implementation");
        }
    }
}
 
Example 2
Source Project: Android-ScalableVideoView   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mVideoView = (ScalableVideoView) findViewById(R.id.video_view);
    findViewById(R.id.btn_next).setOnClickListener(this);

    try {
        mVideoView.setRawData(R.raw.landscape_sample);
        mVideoView.setVolume(0, 0);
        mVideoView.setLooping(true);
        mVideoView.prepare(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mVideoView.start();
            }
        });
    } catch (IOException ioe) {
        //ignore
    }
}
 
Example 3
Source Project: letv   Source File: HotPlayVideoView.java    License: Apache License 2.0 6 votes vote down vote up
public void onCompletion(MediaPlayer mediaPlayer) {
    LogInfo.log("clf", "...arg0.getCurrentPosition().." + mediaPlayer.getCurrentPosition());
    LogInfo.log("clf", "...arg0.getDuration().." + mediaPlayer.getDuration());
    LogInfo.log("clf", "...isComplete..");
    this.isComplete = true;
    this.playTime = 0;
    this.seekBar.setVisibility(8);
    this.image.setVisibility(0);
    this.playButton.setVisibility(0);
    this.loading.setVisibility(8);
    if (this.mVideoView != null) {
        this.mVideoView.pause();
    }
    stopSendHander();
    LogInfo.log("LM", "completion");
    updatePlayDataStatistics("time", (this.timeElapsed - this.lastTimeElapsed) / 1000 == 0 ? (this.timeElapsed - this.lastTimeElapsed) % 1000 : ((this.timeElapsed - this.lastTimeElapsed) / 1000) + 1, this.isAutoPlay);
    updatePlayDataStatistics("end", -1, this.isAutoPlay);
    this.mActivity.setHomeClickNum(0);
    this.mActivity.setUuidTime(null);
    this.mActivity.mIsHomeClicked = false;
    LogInfo.log("jc666", "complete");
}
 
Example 4
@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 5
Source Project: SMP   Source File: MusicService.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSeekComplete(MediaPlayer mp) {
    // on a 4.1 phone no bug : calling getCurrentPosition now gives the new seeked position
    // on My 2.3.6 phone, the phone seems bugged : calling now getCurrentPosition gives
    // last position. So wait the seekpos goes after the asked seekpos.
    if(seekPosBug != -1) {
        // todo: make it thread safe?
        seekPosNbLoop = seekPosMaxLoop;

        final Timer seekPosTimer = new Timer();
        seekPosTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (seekPosNbLoop-- > 0 || getCurrentPosition() >= seekPosBug) {
                    seekFinished = true;
                    seekPosBug = -1;
                    seekPosTimer.cancel();
                }
            }
        }, 300);
    }
    else {
        seekFinished = true;
    }
    Log.d("MusicService", "onSeekComplete setProgress" + RowSong.secondsToMinutes(getCurrentPosition()));
}
 
Example 6
Source Project: FimiX8-RE   Source File: CustomVideoView.java    License: MIT License 6 votes vote down vote up
public void onPrepared(MediaPlayer mediaPlayer) {
    LogUtil.i(TAG, "onPrepare");
    showPlayView();
    this.mPlaySb.setMax(getDuration());
    this.mTotalTimeTv.setText(setTimeFormatter(getDuration()));
    this.mediaPlayer = mediaPlayer;
    if (this.mediaPlayer != null) {
        mediaPlayer.setOnBufferingUpdateListener(this);
        this.mCurrentCount = 0;
        if (this.listener != null) {
            this.listener.onAdVideoLoadSuccess();
        }
        setCurrentPlayState(2);
        resume();
    }
}
 
Example 7
Source Project: myapplication   Source File: BeepManager.java    License: Apache License 2.0 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.scan);
        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 8
public MediaPlayerHolder(Context context) {
    mContext = context;
    EventBus.getDefault().register(this);
    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            stopUpdatingSeekbarWithPlaybackProgress(true);
            logToUI("MediaPlayer playback completed");
            EventBus.getDefault().post(new LocalEventFromMediaPlayerHolder.PlaybackCompleted());
            EventBus.getDefault()
                    .post(new LocalEventFromMediaPlayerHolder.StateChanged(
                            PlayerState.COMPLETED));
        }
    });
    logToUI("mMediaPlayer = new MediaPlayer()");
}
 
Example 9
Source Project: FamilyChat   Source File: HxShortVideoPlayActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void startPlayVideo(String path)
{
    //这里之所以在需要播放视频的时候才能Inflate
    //是因为:如果直接初始化后,视频却需要下载,下载完后再播放,此时VideoView的TextTureView很可能已经被回收了导致黑屏
    ViewStub viewStub = findView(R.id.vs_shortvideo_videoview);
    viewStub.inflate();
    mVideoView = findView(R.id.svv_shortvideo_play);
    try
    {
        mVideoView.setDataSource(path);
        mVideoView.setVolume(1f, 1f);
        mVideoView.setLooping(true);
        mVideoView.prepareAsync(new MediaPlayer.OnPreparedListener()
        {
            @Override
            public void onPrepared(MediaPlayer mp)
            {
                mVideoView.start();
            }
        });
    } catch (IOException e)
    {
        showError(R.string.error_shortvideo_play, true);
    }
}
 
Example 10
Source Project: sopa   Source File: ResourcesManager.java    License: Apache License 2.0 6 votes vote down vote up
public static void prepareManager(Engine engine, GameActivity activity, Camera camera,
    VertexBufferObjectManager vbom, ResourceLoader resourceLoader, StoryService storyService,
    LevelService levelService, SettingsService settingsService, JustPlayScoreService justPlayScoreService) {

    getInstance().engine = engine;
    getInstance().activity = activity;
    getInstance().camera = camera;
    getInstance().vbom = vbom;
    getInstance().resourceLoader = resourceLoader;
    getInstance().storyService = storyService;
    getInstance().levelService = levelService;
    getInstance().musicService = new MusicService(MediaPlayer.create(activity.getApplicationContext(), R.raw.theme),
            true);
    getInstance().settingsService = settingsService;
    getInstance().justPlayScoreService = justPlayScoreService;
}
 
Example 11
Source Project: Yahala-Messenger   Source File: VideoEditorActivity.java    License: MIT License 6 votes vote down vote up
@Override
public boolean onFragmentCreate() {
    videoPath = getArguments().getString("videoPath");
    if (videoPath == null) {
        return false;
    }
    videoPlayer = new MediaPlayer();
    videoPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            Utilities.RunOnUIThread(new Runnable() {
                @Override
                public void run() {
                    onPlayComplete();
                }
            });
        }
    });
    return super.onFragmentCreate();
}
 
Example 12
Source Project: GLEXP-Team-onebillion   Source File: OBVideoPlayer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onSeekComplete(MediaPlayer mp)
{
    if (playAfterPrepare)
        start();
    else
    {
        try
        {
            if (this.seekCompletionBlock != null)
                seekCompletionBlock.run();
        }catch (Exception e)
        {
            MainActivity.log("Seek complete error " + e.getMessage());
        }
    }

}
 
Example 13
Source Project: intent_radio   Source File: IntentPlayer.java    License: MIT License 5 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mp)
{
   if ( mp == player )
   {
      log("Starting....");
      player.start();
      // Invalidate any outstanding stop_soon threads, or the like.
      Counter.time_passes();
      // Allow future restarts after failure.
      failure_ttl = initial_failure_ttl;
      State.set_state(context, State.STATE_PLAY, isNetworkUrl());
   }
}
 
Example 14
Source Project: FamilyChat   Source File: HxCallBaseActivity.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 播放来电铃声
 */
protected void playInComingRingtong(int rawResId)
{
    if (mMediaPlayer == null)
        mMediaPlayer = MediaPlayer.create(this, rawResId);
    mMediaPlayer.setLooping(true);
    mMediaPlayer.start();
}
 
Example 15
@Override
public void onCompletion(MediaPlayer player) {

  if (player != null) {
    if (player.isPlaying()) player.stop();
    player.reset();
    player.release();
    player = null;
  }
}
 
Example 16
Source Project: Field-Book   Source File: CollectActivity.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void playSound(String sound) {
    try {
        int resID = getResources().getIdentifier(sound, "raw", getPackageName());
        MediaPlayer chimePlayer = MediaPlayer.create(CollectActivity.this, resID);
        chimePlayer.start();

        chimePlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }
        });
    } catch (Exception ignore) {
    }
}
 
Example 17
private void playSound(int resId) {
	// Stop current player, if there's one playing
	if (null != mCurrentMediaPlayer) {
		mCurrentMediaPlayer.stop();
		mCurrentMediaPlayer.release();
	}

	mCurrentMediaPlayer = MediaPlayer.create(mContext, resId);
	if (null != mCurrentMediaPlayer) {
		mCurrentMediaPlayer.start();
	}
}
 
Example 18
Source Project: JieCaoVideoPlayer-develop   Source File: JCMediaManager.java    License: MIT License 5 votes vote down vote up
@Override
public void onBufferingUpdate(MediaPlayer mp, final int percent) {
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            if (listener != null) {
                listener.onBufferingUpdate(percent);
            }
        }
    });
}
 
Example 19
Source Project: BookReader   Source File: TypeTextView.java    License: Apache License 2.0 5 votes vote down vote up
private void playAudio(int audioResId) {
    try {
        stopAudio();
        mMediaPlayer = MediaPlayer.create(mContext, audioResId);
        mMediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 20
Source Project: DanDanPlayForAndroid   Source File: AndroidMediaPlayer.java    License: MIT License 5 votes vote down vote up
@Override
public void onPrepared(MediaPlayer mp) {
    AndroidMediaPlayer self = mWeakMediaPlayer.get();
    if (self == null)
        return;

    notifyOnPrepared();
}
 
Example 21
Source Project: Gank.io   Source File: WebVideoPresenter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCompletion(MediaPlayer player) {
  if (player != null) {
    if (player.isPlaying()) player.stop();
    player.reset();
    player.release();
  }
}
 
Example 22
Source Project: BotLibre   Source File: AvatarTestActivity.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void resetVideoErrorListener() {
	videoView.setOnErrorListener(new OnErrorListener() {
		@Override
		public boolean onError(MediaPlayer mp, int what, int extra) {
			Log.wtf("Video error", "what:" + what + " extra:" + extra);
			videoError = true;
			return true;
		}
	});
}
 
Example 23
Source Project: CoolChat   Source File: ChatAdapter.java    License: Apache License 2.0 5 votes vote down vote up
private void playSound(String path) {
    MediaPlayer mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(path);
        mediaPlayer.prepare();
        mediaPlayer.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 24
Source Project: LocationAware   Source File: LocationAwareService.java    License: 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 25
Source Project: prayer-times-android   Source File: MyPlayer.java    License: Apache License 2.0 5 votes vote down vote up
private MediaPlayer getMediaPlayer() {
    if (mediaPlayers == null) return null;
    for (MediaPlayer mp : mediaPlayers) {
        if (mp.isPlaying()) return mp;
    }
    return null;
}
 
Example 26
Source Project: prayer-times-android   Source File: AppSound.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public MediaPlayer createMediaPlayer(Alarm alarm) {
    if (!isDownloaded()) return null;
    MediaPlayer mp = new MediaPlayer();
    try {
        mp.setDataSource(App.get(), getUri());
    } catch (IOException e) {
        Crashlytics.logException(e);
        return null;
    }
    return mp;
}
 
Example 27
private void playSound(int resId) {
	// Stop current player, if there's one playing
	if (null != mCurrentMediaPlayer) {
		mCurrentMediaPlayer.stop();
		mCurrentMediaPlayer.release();
	}

	mCurrentMediaPlayer = MediaPlayer.create(mContext, resId);
	if (null != mCurrentMediaPlayer) {
		mCurrentMediaPlayer.start();
	}
}
 
Example 28
Source Project: MNVideoPlayer   Source File: MNViderPlayer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
//        Log.i(TAG, "发生错误error:" + what);
        if (what != -38) {  //这个错误不管
            showErrorView();
        }
        return true;
    }
 
Example 29
Source Project: Spectaculum   Source File: VideoView.java    License: 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 30
Source Project: fritz-examples   Source File: VideoHairColorActivity.java    License: MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_video);
    videoView = findViewById(R.id.video_view);
    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mediaPlayer.setLooping(true);
            mediaPlayer.setVolume(1, 1);
            mediaPlayer.start();
        }
    });
    progressBar = findViewById(R.id.export_progress);
    progressText = findViewById(R.id.progress_text);

    // Create the segmentation options
    FritzVisionSegmentationPredictorOptions options = new FritzVisionSegmentationPredictorOptions();
    options.confidenceThreshold = HAIR_CONFIDENCE_THRESHOLD;

    // Set the on-device model
    SegmentationOnDeviceModel onDeviceModel = FritzVisionModels.getHairSegmentationOnDeviceModel(ModelVariant.FAST);
    
    // Create the predictor
    hairPredictor = FritzVision.ImageSegmentation.getPredictor(onDeviceModel, options);

    maskOptions = new FritzVisionSegmentationMaskOptions();
    maskOptions.maxAlpha = HAIR_ALPHA;

    // Display the video picker
    Intent filePicker = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
    filePicker.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    startActivityForResult(filePicker, 1);
}