72

I am trying to play a video in android emulator I have the video in my assets folder as well as the raw folder But after doing some research still i cant play video in my emulator i am working on android 2.1 My video format is mp4 so i don't think that should be a problem Could anyone just give me an example code so that i can understand a bit more?

The problem is that the VideoView that I need to display the Video will take only a URI or a File path to point to the Video.

If I save the video in the raw or assets folder I can only get an input stream or a file descriptor and it seems nothing of that can be used to initialize the VideoView.

Update

I took a closer look at the MediaPlayer example and tried to start a MediaPlayer with a FileDescriptor to the assets files as in the code below:

SurfaceView videoView = (SurfaceView) findViewById(gettingStarted)
SurfaceHolder holder = videoView.getHolder();
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
final MediaPlayer player = new MediaPlayer();
player.setDisplay(holder);

player.setDataSource(getAssets().openFd(fileName).getFileDescriptor());
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {

   @Override
   public void onPrepared(MediaPlayer mp) {
      mp.start();
   }
});

Now I get a the following exception:

java.io.FileNotFoundException: This file can not be opened as a file descriptor; it is probably compressed

It seems there is no other way then copying the file to the sdcard on startup and that seems like a waste of time and memory.

Janusz
  • 187,060
  • 113
  • 301
  • 369
Abhishek Talwar
  • 729
  • 1
  • 6
  • 3
  • I think the issue is because mp4 is a compressed format. Check my answer for details – Sephy Aug 21 '10 at 09:35
  • Here explanation about 'raw' floder http://stackoverflow.com/questions/11356601/androidplay-video-from-assets – Roman M Feb 10 '15 at 11:31
  • 1
    The year was 2020 and although I was using android studio 3.6, Android 10 operating system, there was audio in the following videoview, but the image was black. Finally, the codes of this friend worked and I cannot explain how happy I was. None of the ones written as the solution below worked in me for the first time. Fortunately I'm happy to finally solve my problem. Thank you: D – Gorkem KARA Apr 13 '20 at 11:24

13 Answers13

124

## Perfectly Working since Android 1.6 ##

getWindow().setFormat(PixelFormat.TRANSLUCENT);
VideoView videoHolder = new VideoView(this);
//if you want the controls to appear
videoHolder.setMediaController(new MediaController(this));
Uri video = getUriFromRawFile(context, R.raw.your_raw_file);
//if your file is named sherif.mp4 and placed in /raw
//use R.raw.sherif
videoHolder.setVideoURI(video);
setContentView(videoHolder);
videoHolder.start();

And then

public static Uri getUriFromRawFile(Context context, @ResRaw int rawResourceId) {
    return Uri.Builder()
        .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
        .authority(context.getPackageName())
        .path(String.valueOf(rawResourceId))
        .build();
}

## Check complete tutorial ##

piotrek1543
  • 19,130
  • 7
  • 81
  • 94
Sherif elKhatib
  • 45,786
  • 16
  • 89
  • 106
  • 9
    **IMPORTANT:** To use the `R.raw` path, you must put your video in the "res/raw" folder and not under "assets". – Kent Apr 15 '13 at 04:58
  • What is "R" here? aka R.raw? What the type of R variable or this is class? – bialix May 13 '13 at 08:15
  • its not working on micromax canvas 4 , instead its giving StringIndexOutofBound exception – Pranav Sharma Aug 19 '13 at 05:18
  • Also - only works for video formats supported by the native Android – Vaiden Dec 31 '13 at 13:15
  • 1
    if you don't call getWindow().setFormat(PixelFormat.TRANSLUCENT);, make sure you call videoView.setZOrderOnTop(true); on your videoview before playing the video, otherwise it will appear behind your views and you will be very confused; if you get Error(-21851621) then you need to recode your H264 files (H264 for example worked for me with LEAWO Total Media Converter) – EpicPandaForce Dec 08 '15 at 11:29
  • This should be somewhere at the top. Best answer. – Kebab Krabby Feb 18 '21 at 15:59
12
String UrlPath="android.resource://"+getPackageName()+"/"+R.raw.ur file name;
videocontainer.setVideoURI(Uri.parse(UrlPath));
videocontainer.start();

where videocontainer of type videoview.

Bishoy Fakhry
  • 161
  • 1
  • 6
11

Try:

AssetFileDescriptor afd = getAssets().openFd(fileName);
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(), afd.getLength());
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
Jay
  • 141
  • 2
  • 5
  • 2
    The `AssetFileDescriptor` version of `setDataSource` was added in API level 24; OP is asking for something that will work on android 2.3. – Ernest3.14 Dec 08 '16 at 01:53
10

PlayVideoActivity.java:

public class PlayVideoActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);

        VideoView videoView = (VideoView) findViewById(R.id.video_view);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);
        videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.documentariesandyou));
        videoView.start();
    }
}

activity_play_video.xml:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >

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

</LinearLayout>
V-rund Puro-hit
  • 5,518
  • 9
  • 31
  • 50
haotang
  • 5,520
  • 35
  • 46
4

If I remember well, I had the same kind of issue when loading stuff from the asset folder but with a database. It seems that the stuff in your asset folder can have 2 stats : compressed or not.
If it is compressed, then you are allowed 1 Mo of memory to uncompress it, otherwise you will get this kind of exception. There are several bug reports about that because the documentation is not clear. So if you still want to to use your format, you have to either use an uncompressed version, or give an extension like .mp3 or .png to your file. I know it's a bit crazy but I load a database with a .mp3 extension and it works perfectly fine. This other solution is to package your application with a special option to tell it not to compress certain extension. But then you need to build your app manually and add "zip -0" option.
The advantage of an uncompressed assest is that the phase of zip-align before publication of an application will align the data correctly so that when loaded in memory it can be directly mapped.

So, solutions :

  • change the extension of the file to .mp3 or .png and see if it works
  • build your app manually and use the zip-0 option
Sephy
  • 50,022
  • 30
  • 123
  • 131
3

Did you try to put manually Video on SDCard and try to play video store on SDCard ?

If it's working you can find the way to copy from Raw to SDcard here :

android-copy-rawfile-to-sdcard-video-mp4.

Community
  • 1
  • 1
NicoMinsk
  • 1,716
  • 6
  • 28
  • 53
2
VideoView myVideo = (VideoView) rootView.findViewById(R.id.definition_video_view);

//Set video name (no extension)
String myVideoName = "my_video";

//Set app package
String myAppPackage = "com.myapp";

//Get video URI from raw directory
Uri myVideoUri = Uri.parse("android.resource://"+myAppPackage+"/raw/"+myVideoName);

//Set the video URI
myVideo.setVideoURI(myVideoUri);

//Play the video
myVideo.start();

https://gist.github.com/jrejaud/b5eb1b013c27a1f3ae5f

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Jordan Réjaud
  • 472
  • 8
  • 13
  • i tried this but in jelly beans it doesn't work. I don't know if its only because of my phone. But it works on newer devices. – Kairi San Jan 13 '16 at 06:27
2

I found it :

Uri raw_uri = Uri.parse(<package_name>/+R.raw.<video_file_name>);

Personnaly Android found the resource, but can't play it for now. My file is a .m4v

Nabil Gardon
  • 175
  • 1
  • 1
1

I think that you need to look at this -- it should have everything you want.

EDIT: If you don't want to look at the link -- this pretty much sums up what you'd like.

MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1); mp.start();

But I still recommend reading the information at the link.

hwrdprkns
  • 7,525
  • 12
  • 48
  • 69
  • hey thanks dude but i have looked at this page for like million times and have used this line of code. It does play audio files but not the video and i think there is something related with videoview and assets or raw folder. If you have any idea in your head please feel free to share or a piece of code. – Abhishek Talwar Jun 14 '10 at 10:48
  • If I call MediaPlayer.create(contect, R.raw.video) I get the same exception, inside the MediaPlayer class, as if I prepare the Mediaplayer myself with a file descriptor. – Janusz Aug 19 '10 at 12:39
0
  1. Use the MediaPlayer API and the sample code.

  2. Put the media file in raw folder.

  3. Get the file descriptor to the file.

  4. mediaplayer.setDataSource(fd,offset,length); - its a three argument constructor.

  5. Then when onPreared , mediaplayer.start();

Mahesh Babariya
  • 4,560
  • 6
  • 39
  • 54
Khajan
  • 11
  • 1
0

In the fileName you must put the relative path to the file (without /asset) for example:

player.setDataSource(
    getAssets().openFd(**"media/video.mp4"**).getFileDescriptor()
);
Tomik
  • 23,857
  • 8
  • 121
  • 100
digolloco
  • 101
  • 1
  • 3
0

It sounds maybe like you have the same issue as i do. instead of using MP4, is 3GPP possible? i think i used like HandBrake or something as the video converter... you just need to make sure you have the right encoder, like H.264x or something. sorry for being a little vague, it's been a while. Also, if it's possible, don't bother worrying about android 2.1 anymore, and also, something things just WILL NOT WORK IN EMULATOR. so if it works on a lot of devices, then just assume it works (especially with different manufacurers)

here, you can read my problem and how i solved the issue (after a long time and no one had an answer). i explained in a lot more detail here: android media player not working

Community
  • 1
  • 1
David T.
  • 22,301
  • 23
  • 71
  • 123
-2

MainCode

Uri raw_uri=Uri.parse("android.resource://<package_name>/+R.raw.<video_file_name>);

myVideoView=(VideoView)findViewbyID(R.idV.Video_view);

myVideoView.setVideoURI(raw_uri);
myVideoView.setMediaController(new MediaController(this));
myVideoView.start();
myVideoView.requestFocus();

XML

<?xml version="1.0" encoding="utf-8" ?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
        <VideoView
            android:id="+@/Video_View"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
        />
</LinearLayout>
Janusz
  • 187,060
  • 113
  • 301
  • 369
  • This is not working at all. The Uri points just to /2130968576 in the case of my resource. – Janusz Aug 19 '10 at 09:34
  • Yes... this solution does not work. However, it the URI points to 2130968576 is OK, because that's the resource ID and that's a legal way to create a usable URI. – Cristian Dec 17 '10 at 01:01
  • Try review your code. Maybe it seems working for you, @Sandeep. However, this maybe not sufficient to solve it. – David Dimalanta Jun 04 '13 at 08:01