如何从assets文件夹或raw文件夹在android中播放视频? [英] How to play videos in android from assets folder or raw folder?

查看:57
本文介绍了如何从assets文件夹或raw文件夹在android中播放视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 android 模拟器中播放视频我的资产文件夹和原始文件夹中有视频但是做了一些研究后我仍然无法在我的模拟器中播放视频我在 android 2.1 上工作我的视频格式是 mp4,所以我认为这应该不是问题谁能给我一个示例代码,以便我能多了解一点?

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?

问题在于,我需要显示视频的 VideoView 将仅使用 URI 或文件路径来指向视频.

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.

如果我将视频保存在 raw 或 assets 文件夹中,我只能获得输入流或文件描述符,而且似乎没有任何内容可用于初始化 VideoView.

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.

更新

我仔细查看了 MediaPlayer 示例,并尝试使用 FileDescriptor 启动 MediaPlayer 到资产文件,如下面的代码所示:

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();
   }
});

现在我收到以下异常:

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

似乎除了在启动时将文件复制到 sdcard 之外别无他法,这似乎是在浪费时间和内存.

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.

推荐答案

## 自 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();

然后

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();
}

##查看完整教程##

这篇关于如何从assets文件夹或raw文件夹在android中播放视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆