I need to be able to store sound files for my application on sdcard

好久不见. 提交于 2019-12-04 21:51:15
MrCloister

OK so I found the answer!

First we need to get the external Storage Directory to a variable called baseDir.

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();

Then Create the directory mysounds on the SDcard

File folder = new File(Environment.getExternalStorageDirectory() + "/mysounds");
boolean success = false;
if(!folder.exists())
{
    success = folder.mkdir();     
}         
if (!success) 
{ 
    // Do something on success
}
else 
{
    // Do something else on failure 
}

Then This following bit of code will copy all the files with sound at the beginning of the name from the assets directory to the mysounds directory you have already created.

try {
        AssetManager am = getAssets();
        String[] list = am.list("");
        for (String s:list) {
            if (s.startsWith("sound")) {
                Log.d("Notice", "Copying asset file " + s);
                InputStream inStream = am.open(s);
                int size = inStream.available();
                byte[] buffer = new byte[size];
                inStream.read(buffer);
                inStream.close();
                FileOutputStream fos = new FileOutputStream(baseDir + "/mysounds/" + s);
                fos.write(buffer);
                fos.close();
            }
      }
 }

Hope this helps someone!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!