Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/178.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何读取音频文件_Java_Android_Audio_Inputstream_Outputstream - Fatal编程技术网

Java 如何读取音频文件

Java 如何读取音频文件,java,android,audio,inputstream,outputstream,Java,Android,Audio,Inputstream,Outputstream,在一个Android项目中,我将一个音频文件读入InputStream,然后将其写入设备上的另一个位置。读取时,in.read(buffer)返回-1,如代码段所示。运行应用程序后,我使用手机的文件管理器应用程序找到文件进行播放。但它不会播放,因为文件为空,即大小为0字节。使用InputStreams和OutputStreams读取和写入音频文件的正确方法是什么 try { DocumentFile newFile = pickedDir.createFile("audio/mp3", "New

在一个Android项目中,我将一个音频文件读入
InputStream
,然后将其写入设备上的另一个位置。读取时,
in.read(buffer)
返回
-1
,如代码段所示。运行应用程序后,我使用手机的文件管理器应用程序找到文件进行播放。但它不会播放,因为文件为空,即大小为
0字节
。使用
InputStreams
OutputStreams
读取和写入音频文件的正确方法是什么

try {
DocumentFile newFile = pickedDir.createFile("audio/mp3", "New File");
OutputStream out = getContentResolver().openOutputStream(newFile.getUri());
InputStream in = new FileInputStream("/storage/emulated/0/beat.mp3");
// To check whether the source file exists
File testFile = File("/storage/emulated/0/beat.mp3");
Log.d("App", "exists: " + testFile.exists() + " len: " + testFile.length());//exists: true len: 0
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
      out.write(buffer, 0, read);
}
    in.close();
    out.flush();
    out.close();
} catch (Exception e) {
  Log.d("Exception ", e.getMessage());
}
要学究气,请使用:

FileInputStream in = new FileInputStream("/storage/emulated/0/beat.mp3");
只需确保路径正确且文件存在。除此之外,从你提供的信息来看,我想不出其他任何东西

OutputStream out = getContentResolver().openOutputStream(newFile.getUri());
InputStream in = new FileInputStream("/storage/emulated/0/beat.mp3");
File newFile = File("/storage/emulated/0/beat.mp3");

这里的代码似乎有问题,newFile.getUri()在初始化之前被调用?

避免使用硬编码的文件系统路径。请参阅此链接@nandsito noted。但这只是为了演示,你又用saf的东西发布了同样的代码。我建议您只发布代码来读取文件。专注于真正的问题。我也没有看到file.exists()和file.length()。应该在里面的。没有saf。所以你不应该一开始就谈论复制文件。仅读取。@greenapps我已经更新了它,我希望这会更好。谢谢,但结果是一样的。这只是为了检查正在读取的源文件是否确实存在。该代码段已更新,以消除这种混淆。