【问题标题】:save audio file in raw or assets folder to sdcard android将原始或资产文件夹中的音频文件保存到 sdcard android
【发布时间】:2012-02-29 05:22:21
【问题描述】:

大家好,我在资产文件夹中有一个音频文件,我需要将相同的文件保存到 sdcard 上。

如何实现这一点。

下面是我用来保存文件的代码

String filename = "filename.txt";
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos;
byte[] data = new String("data to write to file").getBytes();
try {
    fos = new FileOutputStream(file);
    fos.write(data);
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    // handle exception
} catch (IOException e) {
    // handle exception
}

请帮忙

【问题讨论】:

    标签: android audio android-file


    【解决方案1】:

    试试这个

    AssetManager mngr = getAssets();
    InputStream path = mngr.open("music/music1.mp3"); 
    
                        BufferedInputStream bis = new BufferedInputStream(path,1024);
    
                        //get the bytes one by one
                        int current = 0;
    
                        while ((current = bis.read()) != -1) {
    
                            baf.append((byte) current);
                        }
    }
    byte[] bitmapdata  = baf.toByteArray();
    

    转换成字节数组后复制到sdcard如下

    File file = new File(Environment.getExternalStorageDirectory(), music1.mp3);
    FileOutputStream fos;
    
    try {
        fos = new FileOutputStream(file);
        fos.write(bitmapdata  );
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        // handle exception
    } catch (IOException e) {
        // handle exception
    }
    

    【讨论】:

    • ByteArrayBuffer baf = new ByteArrayBuffer(1024);
    • 嘿这里在 File file = new File(Environment.getExternalStorageDirectory(), music1.mp3); music.mp3 显示错误
    • 嘿,谢谢,我明白了,请你解释一下代码中发生了什么
    • 你正在打开 assets 文件夹中的文件并将其读取到一个字节数组和你正在写入 sdcard 中新创建的文件的相同字节数组
    • 一般来说使用bytearray读写文件是最好的
    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多