Playing a video in VideoView in Android
Asked Answered
S

13

66

I can't figure out why I'm not able to play the video in my 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. Do I need to place my SD card in a particular folder in my 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...

Strom answered 16/7, 2010 at 10:3 Comment(8)
These are the error messages displayed in my Log cat window: 07-16 17:16:30.237: ERROR/PlayerDriver(30): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported 07-16 17:16:30.247: ERROR/MediaPlayer(240): error (1, -4) 07-16 17:16:30.257: ERROR/MediaPlayer(240): Error (1,-4) 07-16 17:16:30.267: DEBUG/VideoView(240): Error: 1,-4 07-16 17:16:30.287: WARN/PlayerDriver(30): PVMFInfoErrorHandlingCompleteStrom
Are you attempting to do this on a device or in the emulator? I don't think the emulator supports video playback. Does the video play OK on the device when loaded from a file manager, e.g. ASTRO?Lowther
I'm trying to play video files on my emulator. I have a simple File Manager that i access from my DDMS. What do you mean by ASTRO?Strom
All of my video files are placed in res/raw folder.Strom
Astro is a file manager from the Android Play market.Diazotize
From resource: #3029217Outbound
blonde secretary, ROFLAquiculture
First of all, check your video from the file manager to see if emulator can play it or not. I had the same problem and at the end I found a mistake in URI. Sounds silly, but I wrote "teXt.mp4" instead of "teSt.mp4"Boondoggle
D
36

My guess is that your video is incompatible with 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). If that video works, and yours does not, then your video is not compatible with 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.

Determination answered 18/8, 2010 at 21:8 Comment(13)
I placed the video you suggested in my res/raw folder and changed to: video.setVideoPath("/sdcard/documentariesandyou.mp4"); But still i am unable to play the video. All i am getting is the message Cannot Play Video "Sorry this video cannot be played". Whats the issue?Strom
@Maxood: Something is up with your device, then. That video has played on everything I've tried it on: G1, DROID, N1, Incredible, etc. In fact, I just played it on an Incredible within the past few hours. Bear in mind that you should never hard-code /sdcard, particularly considering it is wrong on Android 2.2 and select other devices.Determination
We have a newly bought DROID. Now what pre-requisites there have to be to run a video file on Android? Also what should i code instead of /sdcard? Thank youStrom
@Maxood: "Now what pre-requisites there have to be to run a video file on Android?" -- for your DROID? I have no idea. Again, that video played fine on a DROID with Android 2.0 and 2.1. I haven't gotten the 2.2 update yet for the DROID and therefore have not tested the video with that combination. "Also what should i code instead of /sdcard?" -- Environment.getExternalStorageDirectory().Determination
@Maxood: I would also recommend you switch to this code, to make sure it is not something with your implementation: github.com/commonsguy/cw-advandroid/tree/master/Media/Video -- this way, we can be sure the problem is limited to something about your DROID setup. Also, what version of Android is this new DROID running?Determination
The DROID OS version i have is 2.0.1. Now i am not getting the message:This video cannot be played. Despite of using the code of the above link, still the video is not being played yet.Strom
Updated the OS to 2.2. Still video file is not being played in VideoView.Strom
Try to play the video (emulator or real device, wherever you're testing) with the regular default media player on Android first. Then you see if you have at least a supported codec. If that's the case, go into your app/VideoView to debug further. This saves some time in case the issue is not with your app but with the video itself. The documentary&you video should definitely work though. Or you're missing some codes on your host pc that runs the emulator.Anjanetteanjela
Got it sorted out. import android.widget.MediaController; import android.widget.VideoView; videoSingAlong = (VideoView)findViewById(R.id.VideoView); videoSingAlong.setMediaController(mc); Uri uri = Uri.parse("android.resource://com.xxxxx.abc/" + R.raw.abc); videoSingAlong.setVideoURI(uri); videoSingAlong.start(); Thanks to everybody.Strom
btw playing in the emulator is fine these days just make sure to enable User Host GPU within AVD Virtual Device emulator optionsFrijol
@wired00: Yes, though you may need an x86 emulator image as well, depending on the speed of the development machine.Determination
ERROR: There is not a movie download matching your request. Please try again. Guess it didn't last a decade 😔Pantagruel
@BenLeggiero: They appear to have reorganized their site somewhat. All of those contest winners are at web.law.duke.edu/cspd/contest/finalists -- the one that I linked to originally is the "Documentaries and You" one. The direct link to the MP4 is law.duke.edu/cspd/contest/videos/…. I'll update the answer. Thanks for pointing this out!Determination
O
29

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.

enter image description here

activity_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 the documentation, Android should support mp4 H.264 playback (decoding) for all API levels. 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. It uses the powerful ffmpeg command line tool to do the conversion to something that should be playable on all (hopefully?) Android devices. 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. 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

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.

Orthorhombic answered 9/12, 2016 at 13:45 Comment(2)
Hello glad that you got a solution. I'm stuck here. I've a similar problem but my video is in the Firebase Storage. Can you please see this post so that I can get a clue. Please do guide me.Nerva
@PC. I've never used Firebase, but you should should break your problem into smaller pieces. First make sure that Android will play the video if it is stored locally (as in my example above). If that works then try downloading (not streaming) it from Firebase and see if you can get it to play the same way you did when it was local.Orthorhombic
R
8

Make videoView a member variable of your activity class instead of keeping it as local to the onCreate function:

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();  
}
Ricebird answered 22/6, 2012 at 11:56 Comment(2)
This is unrelated to the question and will not change anything.Parkerparkhurst
Nice example, i like your video pathMobocracy
A
5

VideoView can only Stream 3gp videos I recommend this code to stream your video or try a higher version of 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.

Ambidextrous answered 5/6, 2013 at 13:53 Comment(1)
how display current record video ?Moue
W
5

Add android.permission.READ_EXTERNAL_STORAGE in manifest, worked for me

Wigfall answered 17/2, 2015 at 6:52 Comment(2)
For me, the missing internet permission in the manifest was the problem: <uses-permission android:name="android.permission.INTERNET" />Grijalva
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />Meperidine
R
3
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. you can get path of your video stored in external storage by using (Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo")and parse it into Uri. If your video is stored in sdcard/MyVideo/video.mp4 replace "/yourvideo" in code by "/MyVideo/video.mp4"

This works fine for me :) `

Rebuff answered 12/2, 2016 at 7:22 Comment(2)
Please add description to your code sample and format the code.Bostow
@MaciejLach I have added description. Its my first answer on stackoverflow. Thanks for helping me to improve my answer.Rebuff
L
2

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!

Right click on opened project, chose Properties > Android > check the latest version on the right side...

Igor

Lemus answered 19/7, 2010 at 14:16 Comment(2)
I'm required to use 1.6 as my version here. Wonder, if you can tell me how can i update my device's OS to 2.2(Froyo)? ThanksStrom
I have 2.0.1 installed on my DROID. And i am trying to run this code on it but still couldn't succeed. Please let me know whats the issue?Strom
A
2

You can access your SD card via the DDMS

Acrylyl answered 19/7, 2010 at 14:19 Comment(2)
If an Android device(HTC, DROID, etc.) hasn't got an SD card installed then could we be able to play a video in an app on that device?Strom
I'm getting the following error messages in my Log cat window: 07-21 03:35:47.854: ERROR/PlayerDriver(30): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported 07-21 03:35:47.864: ERROR/MediaPlayer(284): error (1, -4) 07-21 03:35:47.872: ERROR/MediaPlayer(284): Error (1,-4)Strom
G
2

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
Video resolution - 176 x 144 px
Video frame rate - 12 fps
Video bitrate - 56 Kbps
Audio codec - AAC-LC
Audio channels - (mono)
Audio bitrate - 24 Kbps

Standard definition (High quality)
Video codec - H.264
Video resolution - 480 x 360 px
Video frame rate - 30 fps
Video bitrate - 500 Kbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 128 Kbps

High definition 720p (N/A on all devices)
Video codec - H.264
Video resolution - 1280 x 720 px
Video frame rate - 30 fps
Video bitrate - 2 Mbps
Audio codec - AAC-LC
Audio channels - 2 (stereo)
Audio bitrate - 192 Kbps

Guidon answered 29/4, 2014 at 8:29 Comment(0)
B
0

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 doesn't support large Video (>300MB). We can get it by using NDK optimization.

Blackford answered 16/4, 2012 at 10:49 Comment(0)
A
0

The problem might be with the Movie format. If it's H264 encoded, make sure it's in baseline profile.

Aestheticism answered 19/3, 2013 at 5:34 Comment(0)
C
0

I have almost same issue with 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.

But I notice that with a lower definition of the video (120x120), it works fine.

So perhaps just a matter of "Size" (and especially with blonde_secretary.3gp video ....)

Coeval answered 25/2, 2015 at 19:20 Comment(0)
H
0
//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 {
        }
Hirsute answered 21/4, 2017 at 13:12 Comment(1)
Could you please give some explanation to your answer?Xerography

© 2022 - 2024 — McMap. All rights reserved.