首页 文章

如何通过将其保存在SD卡或使用应用程序的安装地址来访问raw或assets文件夹中的音频?

提问于
浏览
0

我正在尝试制作一个有一些歌曲的音乐专辑应用程序并且可以播放它们 . 我制作了播放器,但现在我卡住了,因为我的播放器,在SD卡上的特殊地址使用音乐,我需要复制音频或使用设备上安装的应用程序的资产(或行)文件夹(我不知道)如果手机内存上有这个文件夹) . 如果有更好的方法请告诉我 .

这是我的代码:

public class SongsManager {
    // SDCard Path
    final String MEDIA_PATH = new String("/sdcard/piano/");
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    // Constructor
    public SongsManager(){

    }

    /**
     * Function to read all mp3 files from sdcard
     * and store the details in ArrayList
     * */
    public ArrayList<HashMap<String, String>> getPlayList(){
        File home = new File(MEDIA_PATH);

        if (home.listFiles(new FileExtensionFilter()).length > 0) {
            for (File file : home.listFiles(new FileExtensionFilter())) {
                HashMap<String, String> song = new HashMap<String, String>();
                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList
                songsList.add(song);
            }
        }
        // return songs list array
        return songsList;
    }

2 回答

  • 0

    资源文件夹是可读文件夹,您无法将文件从SD卡写入或存储到资源文件夹 . 在准备项目的最终版本之前,您可以先将一些Mp3文件添加到资产文件夹中,然后再将其复制到SD卡 .

    现在,您可以从SD卡或资产访问这些文件 . 您只能使用某些RESTful POST Web服务将SD卡中的Mp3歌曲存储到服务器 .

    以下是将资源从资产复制到SD卡的链接

    How to copy files from 'assets' folder to sdcard?

    希望它会对你有所帮助

  • 0

    您可以检查文件夹是否存在:

    File myFile = new File(myPath);
    if (myFile.exists()) {
        // The folder exists so use the files in this folder
    } else {
        // The folder does not exist so use the assets from the apps raw folder
    }
    

    <Additional>

    您不希望显示assets文件夹的地址(向用户列出应用程序的内部文件结构会很糟糕),但是您可以在应用程序中列出原始目录中的文件,并允许用户选择从他们 . 以下代码从原始文件夹的内容填充数组 soundNames[]soundIds[]

    Field[] fields = R.raw.class.getFields();
    String[] soundNames = new String[fields.length];
    int[] soundIds = new int[fields.length];
    for (int i = 0; i < fields.length; i++) {
        soundNames[i] = fields[i].getName();
        soundIds[i] = getResources().getIdentifier(soundNames[i], null, null);
    }
    

相关问题