开发者

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

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 t开发者_如何学JAVAhe 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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜