android.media.MediaPlayer Java Examples

The following examples show how to use android.media.MediaPlayer. 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: BeepManager.java    From myapplication with 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 #2
Source File: VideoEditorActivity.java    From Yahala-Messenger with 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 #3
Source File: OBVideoPlayer.java    From GLEXP-Team-onebillion with 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 #4
Source File: AndroidAudioPlayer.java    From AntennaPod-AudioPlayer with 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 #5
Source File: MainActivity.java    From Android-ScalableVideoView with 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 #6
Source File: ResourcesManager.java    From sopa with 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 #7
Source File: HotPlayVideoView.java    From letv with 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 #8
Source File: HxShortVideoPlayActivity.java    From FamilyChat with 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 #9
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 #10
Source File: MusicService.java    From SMP with 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 #11
Source File: MediaPlayerHolder.java    From android-simple-mediaplayer with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: CustomVideoView.java    From FimiX8-RE with 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 #13
Source File: AndroidMediaPlayer.java    From DanDanPlayForAndroid with MIT License 5 votes vote down vote up
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
    AndroidMediaPlayer self = mWeakMediaPlayer.get();
    if (self == null)
        return;

    notifyOnBufferingUpdate(percent);
}
 
Example #14
Source File: AndroidMediaPlayer.java    From IjkPlayerDemo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    AndroidMediaPlayer self = mWeakMediaPlayer.get();
    if (self == null)
        return false;

    return notifyOnError(what, extra);
}
 
Example #15
Source File: AndroidMediaPlayer.java    From LivePlayback with Apache License 2.0 5 votes vote down vote up
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
    AndroidMediaPlayer self = mWeakMediaPlayer.get();
    if (self == null)
        return;

    notifyOnBufferingUpdate(percent);
}
 
Example #16
Source File: MainActivity.java    From texturevideoview with Apache License 2.0 5 votes vote down vote up
private void initVideoView() {
    mVideoView.setVideoPath(getVideoPath());
    mVideoView.setMediaController(new MediaController(this));
    mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(final MediaPlayer mp) {
            startVideoPlayback();
            startVideoAnimation();
        }
    });
}
 
Example #17
Source File: ReminderFragment.java    From Medicine-Time- with Apache License 2.0 5 votes vote down vote up
@Override
public void showMedicine(MedicineAlarm medicineAlarm) {
    this.medicineAlarm = medicineAlarm;
    mVibrator = (Vibrator) getContext().getSystemService(VIBRATOR_SERVICE);
    long[] pattern = {0, 1000, 10000};
    mVibrator.vibrate(pattern, 0);

    mMediaPlayer = MediaPlayer.create(getContext(), R.raw.cuco_sound);
    mMediaPlayer.setLooping(true);
    mMediaPlayer.start();

    tvMedTime.setText(medicineAlarm.getStringTime());
    tvMedicineName.setText(medicineAlarm.getPillName());
    tvDoseDetails.setText(medicineAlarm.getFormattedDose());
}
 
Example #18
Source File: PlayerControllerTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrepare_verifyOnPreparedListener() {
    doNothing().when(subject).setUpMediaControl();
    subject.prepare(playerItem);

    verify(subject).setUpMediaControl(false, true);
    verify(videoView).setVideoURI(TEST_URI, false);
    verify(videoView).requestFocus();
    verify(videoView).setOnPreparedListener(prepareListenerCaptor.capture());
    verify(videoView).setOnInfoListener(any(MediaPlayer.OnInfoListener.class));
    verifyOnPreparedListener(prepareListenerCaptor.getValue());
}
 
Example #19
Source File: SamplePlayerActivity.java    From VidEffects with Apache License 2.0 5 votes vote down vote up
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mResources = getResources();
        mMediaPlayer = new MediaPlayer();

        try {
            // Load video file from SD Card
            // File dir = Environment
            // .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            // File file = new File(dir,
            // "sample.mp4");
            // mMediaPlayer.setDataSource(file.getAbsolutePath());
            // -----------------------------------------------------------------------
            // Load video file from Assets directory
            AssetFileDescriptor afd = getAssets().openFd("sample.mp4");
            mMediaPlayer.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
        // Initialize VideoSurfaceView using code
        // mVideoView = new VideoSurfaceView(this);
        // setContentView(mVideoView);
        // or
        setContentView(R.layout.activity_sampleplayer);
        mVideoView = (VideoSurfaceView) findViewById(R.id.mVideoSurfaceView);
        mVideoView.init(mMediaPlayer,
                new DuotoneEffect(Color.parseColor("#3498DB"), Color.YELLOW));
//      If you want to change effect then just call mVideoView.init() again
//      and then call mVideoView.onResume()
    }
 
Example #20
Source File: MusicPlayer.java    From mobile-manager-tool with MIT License 5 votes vote down vote up
/**
 * 缓冲更新
 */
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
    seekBar.setSecondaryProgress(percent);
    int currentProgress = seekBar.getMax() * mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
    Log.d(">>>mediaPlayer:" + currentProgress + "% play", percent + " buffer");
}
 
Example #21
Source File: AndroidMediaPlayer.java    From JZVideoDemo with MIT License 5 votes vote down vote up
@Override
public void onSeekComplete(MediaPlayer mp) {
    AndroidMediaPlayer self = mWeakMediaPlayer.get();
    if (self == null)
        return;

    notifyOnSeekComplete();
}
 
Example #22
Source File: AssetVideoView.java    From ResearchStack with Apache License 2.0 5 votes vote down vote up
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
    mVideoWidth = mp.getVideoWidth();
    mVideoHeight = mp.getVideoHeight();
    if (mVideoWidth != 0 && mVideoHeight != 0) {
        getHolder().setFixedSize(mVideoWidth, mVideoHeight);
        requestLayout();
    }
}
 
Example #23
Source File: FFmpegPreviewActivity.java    From FFmpegRecorder with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_ffmpeg_preview);

	cancelBtn = (Button) findViewById(R.id.play_cancel);
	cancelBtn.setOnClickListener(this);
	
	DisplayMetrics displaymetrics = new DisplayMetrics();
	getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
	surfaceView = (TextureView) findViewById(R.id.preview_video);
	
	RelativeLayout preview_video_parent = (RelativeLayout)findViewById(R.id.preview_video_parent);
	LayoutParams layoutParams = (LayoutParams) preview_video_parent
			.getLayoutParams();
	layoutParams.width = displaymetrics.widthPixels;
	layoutParams.height = displaymetrics.widthPixels;
	preview_video_parent.setLayoutParams(layoutParams);
	
	surfaceView.setSurfaceTextureListener(this);
	surfaceView.setOnClickListener(this);
	
	path = getIntent().getStringExtra("path");
	
	imagePlay = (ImageView) findViewById(R.id.previre_play);
	imagePlay.setOnClickListener(this);
	
	mediaPlayer = new MediaPlayer();
	mediaPlayer.setOnCompletionListener(this);
}
 
Example #24
Source File: MediaPlayerListener.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    int errorType;
    switch (what) {
        case MediaPlayer.MEDIA_ERROR_UNKNOWN:
            switch (extra) {
                case MEDIA_ERROR_MALFORMED:
                    errorType = MEDIA_ERROR_DECODE;
                    break;
                case MEDIA_ERROR_TIMED_OUT:
                    errorType = MEDIA_ERROR_INVALID_CODE;
                    break;
                default:
                    errorType = MEDIA_ERROR_FORMAT;
                    break;
            }
            break;
        case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
            errorType = MEDIA_ERROR_DECODE;
            break;
        case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
            errorType = MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK;
            break;
        default:
            // There are some undocumented error codes for android media player.
            // For example, when surfaceTexture got deleted before we setVideoSuface
            // to NULL, mediaplayer will report error -38. These errors should be ignored
            // and not be treated as an error to webkit.
            errorType = MEDIA_ERROR_INVALID_CODE;
            break;
    }
    nativeOnMediaError(mNativeMediaPlayerListener, errorType);
    return true;
}
 
Example #25
Source File: MedcorderAudioPlugin.java    From flutter_audio with MIT License 5 votes vote down vote up
private boolean startPlay(String fileName, double duration){
  try{
    if (player != null && player.isPlaying()){
      player.stop();
      player.release();
    }
  }catch(Exception e){

  }finally {
    player = null;
  }

  currentPlayingFile = activity.getApplicationContext().getFilesDir() + "/" + fileName + ".aac";
  File file = new File(currentPlayingFile);
  if (file.exists()) {
    Uri uri = Uri.fromFile(file);
    player =  MediaPlayer.create(this.context, uri);
    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
      boolean callbackWasCalled = false;

      @Override
      public synchronized void onCompletion(MediaPlayer mp) {
        if (callbackWasCalled) return;
        callbackWasCalled = true;
        stopPlayTimer();
        updatePlayingWithCode("audioPlayerDidFinishPlaying");
      }
    });
    player.seekTo(new Double(duration).intValue() * 1000);
    player.start();
    startPlayTimer();
    isPlaying = true;
  }else{
    return false;
  }

  return true;
}
 
Example #26
Source File: Jzvd.java    From imsdk-android with MIT License 5 votes vote down vote up
public void onInfo(int what, int extra) {
    Log.d(TAG, "onInfo what - " + what + " extra - " + extra);
    if(extra!=0){
        setTextureViewRotation(extra);
    }
    if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
        if (state == Jzvd.STATE_PREPARED
                || state == Jzvd.STATE_PREPARING_CHANGING_URL) {


            onStatePlaying();//真正的prepared,本质上这是进入playing状态。
        }
    }
}
 
Example #27
Source File: IntentPlayer.java    From intent_radio with 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 #28
Source File: WXVideoView.java    From weex-uikit with MIT License 5 votes vote down vote up
public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) {
  mOnPreparedListener = l;
  if (mVideoView != null) {
    mVideoView.setOnPreparedListener(l);
  }

}
 
Example #29
Source File: JZMediaSystem.java    From JZVideoDemo with MIT License 5 votes vote down vote up
@Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, final int percent) {
    JZMediaManager.instance().mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            if (JZVideoPlayerManager.getCurrentJzvd() != null) {
                JZVideoPlayerManager.getCurrentJzvd().setBufferProgress(percent);
            }
        }
    });
}
 
Example #30
Source File: VideoPlayer.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
@Override
public void onPrepared(MediaPlayer newMediaPlayer) {
  mediaReady = true;
  delayedStart = false;
  mPlayer = newMediaPlayer;
  videoView.setMediaPlayer(mPlayer, true);
  if (delayedStart) {
    Start();
  }
}