mp3没有正确保存到SD;如何将mp3保存到SD卡?

时间:2014-02-14 04:07:33

标签: android inputstream outputstream

过去3个小时左右,我一直在看这个网站。 How to copy files from 'assets' folder to sdcard?

这是我能想到的最好的因为我一次只想复制一个文件。

InputStream in = null;
OutputStream out = null;

public void copyAssets() {

    try {
        in = getAssets().open("aabbccdd.mp3");
        File outFile = new File(root.getAbsolutePath() + "/testf0lder");
        out = new FileOutputStream(outFile);
        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (IOException e) {
        Log.e("tag", "Failed to copy asset file: ", e);
    }

}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
}

我已经想出了如何创建文件并保存文本文件。 http://eagle.phys.utk.edu/guidry/android/writeSD.html

我宁愿将mp3文件保存到sdcard而不是文本文件。

当我使用我提供的代码时,我得到一个与aabbccdd.mp3文件大小相同的文本文档。它不会创建文件夹并保存.mp3文件。它将文本文档保存在根文件夹中。当你打开它时,我看到一大堆中文字母,但在英文的顶部我可以看到WireTap这个词。 WireTap Pro是我用来录制声音的程序,所以我知道.mp3正在通过。它只是没有创建一个文件夹,然后像上面的.edu示例一样保存文件。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

我认为你应该做那样的事情 - [注意:这个我用于其他一些格式而不是mp3,但是它在我的应用程序上用于多种格式,所以我希望它也适用于你。]

  InputStream in  = this.getAssets().open("tmp.mp3"); //give path as per ur app         
  byte[] data = getByteData(in);

确保路径中已存在该文件夹,如果文件夹不存在,则无法正确保存内容。

  byteArrayToFile(data , "testfolder/tmp.mp3"); //as per ur sdcard path, modify it.

现在方法::

1)来自inputstream的getByteData -

   private byte[] getByteData(InputStream is) 
   {                        
     byte[] buffer= new byte[1024]; /* or some other number */
     int numRead;
     ByteArrayOutputStream bytes = new ByteArrayOutputStream();
     try{           
        while((numRead = is.read(buffer)) > 0) {
            bytes.write(buffer, 0, numRead);
        }           
        return bytes.toByteArray();
    }
    catch(Exception e)
    { e.printStackTrace(); }        
    return new byte[0];     
   }

2)byteArrayToFile

    public void byteArrayToFile(byte[] byteArray, String outFilePath){      
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(outFilePath);
        fos.write(byteArray);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }        
     }
相关问题