代码之家  ›  专栏  ›  技术社区  ›  Daniele

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

  •  0
  • Daniele  · 技术社区  · 7 年前

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

    根据Commonware的建议,我尝试过这样做,但没有创建文件:

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   CommonsWare    7 年前

    但文件不在那里

    song.getPath() 不太可能有用。 song 可能没有 file getPath()

    使用 ContentResolver openInputStream() InputStream 在…上 歌曲 输入流