Search code examples
androidfileandroid-file

Copy audio from uri to specific directory


I get a song from the user's library like this:

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

and retrieve it like this:

 @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
            }
        }
    }

I need to import it into a folder I defined and created like this:

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

I tried like this as suggested by Commonsware but the file is not created:

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. How can I fix this?


Solution

  • The file is not there though

    Most likely, you have a stack trace in LogCat. song.getPath() is unlikely to be useful. song probably does not have a file scheme, and so getPath() is meaningless.

    Use ContentResolver and openInputStream() to get an InputStream on song, then use that InputStream to copy the content.

    Also: