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

删除回忆录丶 提交于 2019-12-22 00:27:53

问题


I've read a lot of topics but none seem to cover what I need.

I basically have a load of sound files and I want to be able to play them in the application from the sdcard.

I also want to be able to install them there in the first place when the application is installed.

I am using Eclipse with the android SDK and currently my Target project is v1.6

Can anyone help?

Thanks


回答1:


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!



来源:https://stackoverflow.com/questions/5732565/i-need-to-be-able-to-store-sound-files-for-my-application-on-sdcard

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