我有一个方法是将copy an Audio file from raw folder to SD card
。它需要两个输入将RAW文件到SD卡中的Android
- ressound:.ogg音频原始文件ID。
- fName:SD卡中原始文件的文件名。
更新
public boolean saveas(int ressound, String fName){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path="/sdcard/music/[my_package_name]/";
String filename=fName+".ogg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String completePath = baseDir + File.separator + "music" + File.separator + "my_package" + File.separator + filename;
boolean exists = (new File(completePath)).exists();
if (!exists){new File(completePath).mkdirs();}
FileOutputStream save;
try {
save = new FileOutputStream(completePath);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "exampletitle");
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "cssounds ");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, true);
//Insert it into the database
this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);
return true;
}
如果该方法返回true,则该文件被正确保存到SD卡。如果它返回false,那么就有错误。在我的情况下,该方法在输入FileNotFoundException
块时返回false。我找不到原因!一切对我来说都很好。
如果你问我,如果我添加写权限,我把它添加到应用程序标签在清单文件:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
任何帮助吗?
建议使用'文件F = Environment.getExternalStorageDirectory();'为获得SD卡目录中的设备independed方式。 – Im0rtality