本文介绍了播放位于 assets 文件夹中的媒体文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在 android 项目的原始文件夹中有一组媒体文件,这些文件在使用 mediaplayer 类调用时可以快速加载和播放.我需要添加这些文件的更多变体并将它们分类到文件夹中,但显然原始文件夹不支持文件夹.我是否能够从资产文件夹中快速加载这些文件并使用媒体播放器播放它们?如果是,怎么办?

I currently have a set of media files in the raw folder of the android project that are loaded quickly and played when called using the mediaplayer class. I need to add more variations of these files and categorize them into folders, but apparently the raw folder does not support folders. Would I be able to quickly load these files from the assets folder and play them with mediaplayer? If so, how?

推荐答案

我有这个方法可以通过扩展名返回资产文件夹内文件夹中的所有文件:

I've this method that returns the all files by extension in a folder inside asset folder:

public static String[] getAllFilesInAssetByExtension(Context context, String path, String extension){
        Assert.assertNotNull(context);

        try {
            String[] files = context.getAssets().list(path);

            if(StringHelper.isNullOrEmpty(extension)){
                return files;
            }

            List<String> filesWithExtension = new ArrayList<String>();

            for(String file : files){
                if(file.endsWith(extension)){
                    filesWithExtension.add(file);
                }
            }

            return filesWithExtension.toArray(new String[filesWithExtension.size()]);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

如果你使用:

getAllFilesInAssetByExtension(yourcontext, "", ".mp3");

这将返回assets文件夹根目录中的所有mp3文件.

this will return all my mp3 files in the root of assets folder.

如果你使用:

getAllFilesInAssetByExtension(yourcontext, "somefolder", ".mp3");

这将在某个文件夹"中搜索 mp3 文件

this will search in "somefolder" for mp3 files

既然你已经列出了所有要打开的文件,你将需要这个:

Now that you have list all files to open you will need this:

AssetFileDescriptor descriptor = getAssets().openFd("myfile");

播放文件只需:

MediaPlayer player = new MediaPlayer();

long start = descriptor.getStartOffset();
long end = descriptor.getLength();

player.setDataSource(this.descriptor.getFileDescriptor(), start, end);
player.prepare();

player.setVolume(1.0f, 1.0f);
player.start();

希望能帮到你

这篇关于播放位于 assets 文件夹中的媒体文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 03:44