简体   繁体   English

在 Android 中的 VideoView 中播放视频

[英]Playing a video in VideoView in Android

I can't figure out why I'm not able to play the video in my VideoView.我不明白为什么我不能在我的 VideoView 中播放视频。 All I'm getting for a message is:我收到的消息是:

Cannot Play Video : Sorry, this video cannot be played.无法播放视频:抱歉,此视频无法播放。

I created an SD card for my emulator as well.我也为我的模拟器创建了一个 SD 卡。 Do I need to place my SD card in a particular folder in my SDK?我需要将我的 SD 卡放在我的 SDK 中的特定文件夹中吗? Please comment.请给出意见。

Here's the layout:这是布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
   android:id="@+id/LinearLayout01"
   android:layout_height="fill_parent"     
   android:paddingLeft="2px"
   android:paddingRight="2px"
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:paddingTop="2px"
   android:paddingBottom="2px"
   android:layout_width="fill_parent"
   android:orientation="vertical">

      <VideoView 
         android:layout_height="fill_parent"
         android:layout_width="fill_parent" 
         android:id="@+id/VideoView" />

</LinearLayout>

Here's the code:这是代码:

package com.examples.videoviewdemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoViewDemo extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        VideoView videoView = (VideoView)findViewById(R.id.VideoView);
        //MediaController mediaController = new MediaController(this);
        // mediaController.setAnchorView(videoView);
        //videoView.setMediaController(mediaController);

        videoView.setVideoPath("/sdcard/blonde_secretary.3gp");

        videoView.start();  
    }
}

Waiting for the reply...等待回复...

My guess is that your video is incompatible with Android.我的猜测是您的视频与 Android 不兼容。 Try it with a different video.用不同的视频试试。 This one definitely works used to work with Android (but does not on newer devices, for some reason). 这个肯定 适用 于Android(但由于某种原因不适用于较新的设备)。 If that video works, and yours does not, then your video is not compatible with Android.如果该视频有效,而您的无效,则您的视频与 Android 不兼容。

As others have indicated, please test this on a device.正如其他人所指出的,请在设备上进行测试。 Video playback on the emulator requires too much power.在模拟器上播放视频需要太多电量。

UPDATE 2020-02-18 : https://law.duke.edu/cspd/contest/videos/Framed-Contest_Documentaries-and-You.mp4 is an MP4 of the same content, but I have no idea if it is the same actual MP4 as I previously linked to. 2020-02-18 更新https : //law.duke.edu/cspd/contest/videos/Framed-Contest_Documentaries-and-You.mp4是相同内容的 MP4,但我不知道它是否相同我之前链接到的实际 MP4。

Example Project示例项目

I finally got a proof-of-concept project to work, so I will share it here.我终于得到了一个可以工作的概念验证项目,所以我将在这里分享。

Set up the layout设置布局

The layout is set up like this, where the light grey area is the VideoView .布局是这样设置的,其中浅灰色区域是VideoView

在此处输入图片说明

activity_main.xml活动_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.videotest.MainActivity">

    <VideoView
        android:id="@+id/videoview"
        android:layout_width="300dp"
        android:layout_height="200dp"/>

    <Button
        android:text="Play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/videoview"
        android:onClick="onButtonClick"
        android:id="@+id/button"/>

</RelativeLayout>

Prepare video clip准备视频剪辑

According to thedocumentation , Android should support mp4 H.264 playback (decoding) for all API levels.根据文档,Android 应该支持所有 API 级别的 mp4 H.264 播放(解码)。 However, there seem to be a lot of factors that affect whether an actual video will play or not.但是,似乎有很多因素会影响实际视频是否会播放。 The most in depth answer I could find that told how to encode the videos is here .我能找到的关于如何编码视频的最深入的答案是here It uses the powerful ffmpeg command line tool to do the conversion to something that should be playable on all (hopefully?) Android devices.它使用强大的ffmpeg命令行工具来转换为应该可以在所有(希望?)Android 设备上播放的内容。 Read the answer I linked to for more explanation.阅读我链接的答案以获取更多解释。 I used a slightly modified version because I was getting errors with the original version.我使用了一个稍微修改过的版本,因为原始版本出现错误。

ffmpeg -y -i input_file.avi -s 432x320 -b:v 384k -vcodec libx264 -flags +loop+mv4 -cmp 256 -partitions +parti4x4+parti8x8+partp4x4+partp8x8 -subq 6 -trellis 0 -refs 5 -bf 0 -coder 0 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -qmin 10 -qmax 51 -qdiff 4 -c:a aac -ac 1 -ar 16000 -r 13 -ab 32000 -aspect 3:2 -strict -2 output_file.mp4

I would definitely read up a lot more on each of those parameters to see which need adjusting as far as video and audio quality go.我肯定会阅读更多关于每个参数的信息,看看哪些参数需要在视频和音频质量方面进行调整。

Next, rename output_file.mp4 to test.mp4 and put it in your Android project's /res/raw folder.接下来,将output_file.mp4重命名为test.mp4并将其放入您的 Android 项目的/res/raw文件夹中。 Create the folder if it doesn't exist already.如果文件夹不存在,则创建该文件夹。

Code代码

There is not much to the code.代码不多。 The video plays when the "Play" button is clicked.单击“播放”按钮时会播放视频。 Thanks to this answer for help.感谢这个答案的帮助。

MainActivity.java主活动.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onButtonClick(View v) {
        VideoView videoview = (VideoView) findViewById(R.id.videoview);
        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.test);
        videoview.setVideoURI(uri);
        videoview.start();
    }
}

Finished完成的

That's all.就这样。 You should be able play your video clip on the simulator or a real device now.您现在应该可以在模拟器或真实设备上播放您的视频剪辑了。

Make videoView a member variable of your activity class instead of keeping it as local to the onCreate function:使videoView成为活动类的成员变量,而不是将其作为onCreate函数的本地变量:

VideoView videoView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    videoView = (VideoView)findViewById(R.id.VideoView);        
    videoView.setVideoPath("/sdcard/blonde_secretary.3gp");
    videoView.start();  
}

VideoView can only Stream 3gp videos I recommend this code to stream your video or try a higher version of android. VideoView 只能流式传输 3gp 视频我推荐此代码来流式传输您的视频或尝试更高版本的 android。 Try Video Online Streaming.尝试视频在线流媒体。

public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.main);
    String videourl = "http://something.com/blah.mp4";
    Uri uri = Uri.parse(videourl);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.setDataAndType(uri, "video/mp4");
    startActivity(intent);
}

Or Click here to watch Android Video Streaming Tutorial .单击此处观看 Android 视频流教程

在清单中添加 android.permission.READ_EXTERNAL_STORAGE,对我有用

VideoView videoView =(VideoView) findViewById(R.id.videoViewId);

Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo");

 videoView.setVideoURI(uri);
videoView.start();

Instead of using setVideoPath use setVideoUri.而不是使用 setVideoPath 使用 setVideoUri。 you can get path of your video stored in external storage by using (Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo")and parse it into Uri.您可以使用 (Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo") 获取存储在外部存储中的视频的路径并将其解析为 Uri。 If your video is stored in sdcard/MyVideo/video.mp4 replace "/yourvideo" in code by "/MyVideo/video.mp4"如果您的视频存储在 sdcard/MyVideo/video.mp4 中,请将代码中的“/yourvideo”替换为“/MyVideo/video.mp4”

This works fine for me :) `这对我来说很好用 :) `

To confirm you video is in the correct format (resolution, bitrate, codec, etc.) check with the official documentation - extract below:要确认您的视频格式正确(分辨率、比特率、编解码器等),请查看 官方文档- 摘录如下:

Standard definition (Low quality)标准清晰度(低质量)
Video codec - H.264视频编解码器 - H.264
Video resolution - 176 x 144 px视频分辨率 - 176 x 144 像素
Video frame rate - 12 fps视频帧率 - 12 fps
Video bitrate - 56 Kbps视频比特率 - 56 Kbps
Audio codec - AAC-LC音频编解码器 - AAC-LC
Audio channels - (mono)音频通道 -(单声道)
Audio bitrate - 24 Kbps音频比特率 - 24 Kbps

Standard definition (High quality)标清(高质量)
Video codec - H.264视频编解码器 - H.264
Video resolution - 480 x 360 px视频分辨率 - 480 x 360 像素
Video frame rate - 30 fps视频帧率 - 30 fps
Video bitrate - 500 Kbps视频比特率 - 500 Kbps
Audio codec - AAC-LC音频编解码器 - AAC-LC
Audio channels - 2 (stereo)音频通道 - 2(立体声)
Audio bitrate - 128 Kbps音频比特率 - 128 Kbps

High definition 720p (N/A on all devices)高清 720p(在所有设备上不适用)
Video codec - H.264视频编解码器 - H.264
Video resolution - 1280 x 720 px视频分辨率 - 1280 x 720 像素
Video frame rate - 30 fps视频帧率 - 30 fps
Video bitrate - 2 Mbps视频比特率 - 2 Mbps
Audio codec - AAC-LC音频编解码器 - AAC-LC
Audio channels - 2 (stereo)音频通道 - 2(立体声)
Audio bitrate - 192 Kbps音频比特率 - 192 Kbps

The code seems to be flawless!代码似乎完美无缺! Simple and plain.简单明了。
So it should work on the phone.所以它应该在手机上工作。 The emulator is having hard time playing videos, it happened to me too.模拟器很难播放视频,这也发生在我身上。

Try increasing the required API level to the latest, it might help!尝试将所需的 API 级别提高到最新,它可能会有所帮助!

Right click on opened project, chose Properties > Android > check the latest version on the right side...右键单击打开的项目,选择“属性”>“Android”> 在右侧检查最新版本...

Igor伊戈尔

您可以通过 DDMS 访问您的 SD 卡

Well !好 ! if you are using a android Compatibility Video then the only cause of this alert is you must be using a video sized more then the 300MB.如果您使用的是 android 兼容性视频,那么此警报的唯一原因是您必须使用大小超过 300MB 的视频。 Android doesn't support large Video (>300MB). Android 不支持大视频 (>300MB)。 We can get it by using NDK optimization.我们可以通过使用 NDK 优化来获得它。

The problem might be with the Movie format.问题可能出在电影格式上。 If it's H264 encoded, make sure it's in baseline profile.如果它是 H264 编码的,请确保它在基线配置文件中。

I have almost same issue with VideoView.我对 VideoView 有几乎相同的问题。 I try to play a video (1080*1080) with a Nexus 5 and it works well, but the same video on Galaxy ace 2 give me the Cannot Play Video message.我尝试使用 Nexus 5 播放视频 (1080*1080) 并且效果很好,但 Galaxy ace 2 上的相同视频给我无法播放视频消息。

But I notice that with a lower definition of the video (120x120), it works fine.但我注意到视频的清晰度较低(120x120),效果很好。

So perhaps just a matter of "Size" (and especially with blonde_secretary.3gp video ....)所以也许只是一个“大小”的问题(尤其是blonde_secretary.3gp视频......)

//just copy this code to your main activity.

 if ( ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ){
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)){

            }else {
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},1);
            }
        }else {
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM