首页 > 解决方案 > 为什么我不能从 VideoView 播放我的视频?

问题描述

我已经非常接近播放视频了,但我仍然遇到问题。这是我的代码MainActivity.java

public void my_vid(View view){
setContentView(R.layout.my_vid);
        VideoView vid = findViewById(R.id.video_view);
        String vid_path = "/sdcard/Download/Track_horizontal_plane.mp4";
        Uri uri = Uri.parse(vid_path);
        vid.setVideoURI(uri);
        MediaController mediaController = new MediaController(this);
        vid.setMediaController(mediaController);
        mediaController.setAnchorView(vid);

    }

这是我的相关布局:

<VideoView
        android:id="@+id/video_view"
        android:layout_width="411dp"
        android:layout_height="667dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

最后,这是我得到的错误:

2020-12-16 12:40:15.204 25622-25622/com.android.choice D/MediaPlayerNative: getMetadata
2020-12-16 12:40:26.286 25622-25654/com.android.choice E/MediaPlayerNative: error (100, 2)
2020-12-16 12:40:26.287 25622-25622/com.android.choice E/MediaPlayer: Error (100,2)
2020-12-16 12:40:26.287 25622-25622/com.android.choice D/VideoView: Error: 100,2
2020-12-16 12:40:26.302 25622-25654/com.android.choice E/MediaPlayerNative: error (1, -2147479551)
2020-12-16 12:40:26.401 25622-25622/com.android.choice E/MediaPlayer: Error (1,-2147479551)
2020-12-16 12:40:26.401 25622-25622/com.android.choice D/VideoView: Error: 1,-2147479551

当我打开包含 VideoView 的内容布局时,MediaController 工作,甚至可以正确告诉我我选择的视频的长度。一旦我在媒体控制器上点击播放,它就会告诉我视频无法播放。该文件是一个mp4文件,所以我认为应该没有问题。知道我哪里出错了吗?谢谢您的帮助。

标签: javaandroidandroid-videoview

解决方案


1.请确保您从硬编码字符串中解析 URI 是正确的。如果您尝试使用实际的 URI,它可能会更好。在这里您可以看到从图库获取视频的示例。

  fun chooseVideoFromGallery() {
    val intent = Intent()
    intent.type = "video/mp4"
    intent.action = Intent.ACTION_GET_CONTENT
    startActivityForResult(
        Intent.createChooser(intent, "Select Video"),
        REQUEST_TAKE_GALLERY_VIDEO
    )
}


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
            val uri: Uri? = data!!.data
         
        }
    } 
}

2.如果问题不在于 URI,那么最好使用 Exo 播放器(由 google 构建)而不是视频播放器,这样可以支持广泛的视频和音频容器。


推荐阅读