How to play videos in android from assets folder or raw folder?
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.
Solution 1:
## 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 ##
Solution 2:
String UrlPath="android.resource://"+getPackageName()+"/"+R.raw.ur file name;
videocontainer.setVideoURI(Uri.parse(UrlPath));
videocontainer.start();
where videocontainer of type videoview.
Solution 3:
Try:
AssetFileDescriptor afd = getAssets().openFd(fileName);
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(), afd.getLength());