-1

我一直在谷歌上搜索很多解决方案,但它们不起作用。我对 Uri 还不太熟悉,路径被传递给函数和 Inputstreams 在存储文件中输入/输出。

我的项目允许用户从外部存储附加音频文件,并获取其 Uri

从按钮 setOnclick

acs.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(
                    lol, "Open Audio (mp3) file"), RQS_OPEN_AUDIO_MP3);

(这是来自 onActivityResult 函数)

if (resultCode == RESULT_OK) {
        if (requestCode == RQS_OPEN_AUDIO_FX) {
            audioFxUri = data.getData();
        }
}

我想要做的是将音频存储到其内部存储中。

您能帮忙将音频文件存储在内部存储器中的代码吗?它是否也经历了文件到字节数组然后字节数组到文件的过程(带有内部存储的位置)?

我只是根据我到目前为止所看到的。希望你的代码帮助我。

4

1 回答 1

0

您可以将其复制到应用程序文件目录:getApplicationContext().getFilesDir().getAbsolutePath()

public Uri copyFile(Uri uri){

    if (uri == null) {
        return null;
    }

    String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(getApplicationContext().getContentResolver().getType(uri));

    String fileName = "some_name" + "." + extension;

    File tempFile = new File(getApplicationContext().getFilesDir().getAbsolutePath(), fileName);

    try {

        boolean fileCreated = tempFile.createNewFile();

        if(!fileCreated){
            Log.e(LOG_TAG,"error creating file");
        }

        InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(uri);

        if(inputStream != null){
            IOUtils.copy(inputStream, new FileOutputStream(tempFile));
        }
    } catch (IOException | NullPointerException ex) {
        Log.d(LOG_TAG, "Exception caught: " + ex.getMessage());
    }

    return Uri.fromFile(tempFile);
}
于 2018-10-24T18:33:41.410 回答