📅  最后修改于: 2020-10-11 03:44:38             🧑  作者: Mango
借助MediaController和VideoView类,我们可以在android中播放视频文件。
android.widget.MediaController是一个视图,其中包含媒体控件,例如播放/暂停,上一个,下一个,快进,快退等。
android.widget.VideoView类提供了播放和控制视频播放器的方法。 VideoView类的常用方法如下:
Method | Description |
---|---|
public void setMediaController(MediaController controller) | sets the media controller to the video view. |
public void setVideoURI (Uri uri) | sets the URI of the video file. |
public void start() | starts the video view. |
public void stopPlayback() | stops the playback. |
public void pause() | pauses the playback. |
public void suspend() | suspends the playback. |
public void resume() | resumes the playback. |
public void seekTo(int millis) | seeks to specified time in miliseconds. |
从面板上拖动VideoView,现在activity_main.xml文件将如下所示:
让我们编写播放视频文件的代码。在这里,我们将播放sdcard / media目录中的1.mp4文件。
package com.example.video1;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView =(VideoView)findViewById(R.id.videoView1);
//Creating MediaController
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
//specify the location of media file
Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/media/1.mp4");
//Setting MediaController and URI, then starting the videoView
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
您需要在真实设备(例如移动设备)上运行它以测试应用程序。