【问题标题】:Copy audio from uri to specific directory将音频从 uri 复制到特定目录
【发布时间】:2018-02-24 18:02:29
【问题描述】:

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

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();
        }
    }
}

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

【问题讨论】:

    标签: android file android-file


    【解决方案1】:

    文件不存在

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

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

    还有:

    【讨论】:

    • 感谢您的回答,我将使用InputStream 进行此操作。只是出于好奇,Uri 对象中的getPath() 方法实际上有什么用?还基于这里关于 SO 的其他问题,它对我来说是接缝,因为它是一种非常令人困惑的方法,我仍然无法弄清楚如何以及何时使用它。也感谢索引提示会很有用,我不知道
    • @Daniele:“出于好奇,Uri 对象中的 getPath() 方法实际上有什么用处?” -- 如果 scheme 是file,它是一个文件系统路径。如果该方案是别的什么,它是一系列字符,其含义对您来说是不透明的。例如,https://stackoverflow.com/questions/46241361/android-copy-audio-from-uri-to-specific-directory/46241452Uri。它的方案是https。它的路径是/questions/46241361/android-copy-audio-from-uri-to-specific-directory/46241452,这只是一系列对你的应用没有意义的字符。
    • 拜托,你能看看更新的答案吗?我试着按照你的建议做,但没有运气。文件未创建
    • @Daniele:检查 LogCat 中来自您的 catch 块和 index the destination file 的错误消息(请参阅我的答案中的两个项目符号)。
    • 我已经实现了权限和索引,即使文件管理器不应该基于 MediaStore 以使文件可见
    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 2012-01-19
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多