由于限制,我需要在第一次启动时下载一个wav文件。
我将该文件托管在服务器foo.bar/foo.wav上。
如果我打开指向该url连接,并将其通过管道传输到剪辑中,则音频播放正常。
我使用以下命令来完成此操作:
public static AudioInputStream downloadSound(String link) {
URL url;
try {
url = new URL(link);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream is = urlConn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
AudioInputStream soundInput = AudioSystem.getAudioInputStream(bis);
// Starting the clip here also works perfectly
return soundInput;
} catch (IOException | UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}现在,当我想要保护输入流到一个wav文件时,使用:
public void saveSound(AudioInputStream stream, String name) {
this.createFolderIfNotExist("/sound");
File soundfile = new File(mainPath + "/sound/" + name);
Clip clip;
try {
clip = AudioSystem.getClip();
clip.open(stream);
clip.start();
// The Clip starts normally here. ( this block is just for testing purposes)
} catch (LineUnavailableException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
AudioSystem.write(stream, AudioFileFormat.Type.WAVE, soundfile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}现在我的问题是,只有音频的一部分,准确地说是1秒,被保存到wav文件中。
我已经检查过了,我在服务器上有完整的文件,我也进行了验证,将音频输入流传输到一个剪辑中,然后播放它播放完整的音频。
现在我的问题是:我如何将完整的流写入文件,还是必须这样做,这样才能更简单地将wav文件下载到特定位置
发布于 2020-12-22 06:57:40
好了,我已经找到了解决我的问题的方法,而不是从服务器获取audioInputStream,我只是将流作为普通流来处理,并使用java io的文件编写它。
public static void downloadSoundandSave(String url, String name) {
Filesystem filesystem = new Filesystem();
try (InputStream in = URI.create(url).toURL().openStream()) {
filesystem.createFolderIfNotExist("/sound");
Files.copy(in, Paths.get(filesystem.getMainPath() + "/sound/" + name));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}https://stackoverflow.com/questions/65397501
复制相似问题