I need to be able to store sound files for my appl

2020-08-02 11:25发布

问题:

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!