【问题标题】:android raw mp3 resource to native android media storageandroid raw mp3 资源到原生 android 媒体存储
【发布时间】:2025-12-21 18:15:12
【问题描述】:

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

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

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

How can I download a song and add it the user's music library?

【问题讨论】:

    标签: android mp3 local-storage android-mediaplayer


    【解决方案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 文件),但如果您想加快处理速度,可以使用您在问题中提到的链接。

    【讨论】:

      最近更新 更多