0

我正在尝试将嵌入在我的应用程序中的 mp3 资源保存到 android 设备。这样我以后可以在默认的 android 媒体播放器中播放它。

我可以得到我的资源的输入流没有问题。但我不能让它以默认的 Java 方式保存到设备中。

这两种解决方案似乎都不适合我:

如何下载歌曲并将其添加到用户的音乐库?

4

1 回答 1

1

首先确保您的应用程序具有适当的权限,包括android.permission.WRITE_EXTERNAL_STORAGE

然后,您可以将文件从您的资源复制到 android 设备。这是一个示例代码,仅用于说明目的,请根据需要进行更改:

private void copyMp3() throws IOException{

// Open your mp3 file as the input stream
InputStream myInput = getAssets().open("your_file.mp3");

// Path to the output file on the device
String outFileName = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_MUSIC),"your_file.mp3");

OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0 ){
   myOutput.write(buffer, 0, length);
}

//Close the streams => Better to have it in *final* block
myOutput.flush();
myOutput.close();
myInput.close();

}

媒体扫描仪应自行选择文件(除非该文件夹中有 .nomedia 文件),但如果您想加快该过程,您可以使用您在问题中提到的链接。

于 2013-02-04T22:27:42.027 回答