将音频从 uri 复制到特定目录

Copy audio from uri to specific directory

我从用户的曲库中得到一首这样的歌曲:

Intent selectIntent = new Intent(Intent.ACTION_GET_CONTENT);
            selectIntent.setType("audio/*");
            startActivityForResult(selectIntent, SONG_REQUEST_CODE);

并像这样检索它:

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SONG_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            if ((data != null) && (data.getData()!=null)) {
                song = data.getData(); //song is an Uri defined previuosly
            }
        }
    }

我需要将它导入到我这样定义和创建的文件夹中:

final File dir2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Chords/Imported Audio");
dir2.mkdirs();

我按照 Commonsware 的建议进行了尝试,但未创建文件:

private void importAudio(Uri uri) {
    String source = uri.getPath();
    String destinationFile = dir2 + File.separator + songName;

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    try {
        bis = new BufferedInputStream(new FileInputStream(source));
        bos = new BufferedOutputStream(new FileOutputStream(destinationFile, false));

        byte[] buf = new byte[1024];
        bis.read(buf);
        do {
            bos.write(buf);
        } while (bis.read(buf) != -1);

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null) bis.close();
            if (bos != null) bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

文件不存在。我该如何解决这个问题?

The file is not there though

很可能,您在 LogCat 中有一个堆栈跟踪。 song.getPath() 不太可能有用。 song 可能没有 file 方案,所以 getPath() 没有意义。

使用 ContentResolveropenInputStream()song 上获得 InputStream,然后使用 InputStream 复制内容。

还有:

  • 以便在更多应用程序和桌面操作系统中看到它