Due to restrictions, i need to download a wav file on the first startup.
I have that file hosted on server foo.bar/foo.wav
.
If i open a Connection to that url and pipe that into a clip, the audio plays fine.
Im doing this using:
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;
}
Now, when i want to safe the inputstream to a wav file using:
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();
}
}
Now my Problem is, that only a part of the audio, to be precise 1s, gets saved into the wav file.
I've already checked and i have the complete file on the server, i also have verified, piping the audioinputstream into a Clip and playing it plays the complete audio.
Now my question: How do i write the complete stream to a file or do i even have to do it this way and this there an simpler way to download that wav file to a specific location
Well, i've found a workaround for my problem, now instead of getting the audioInputStream from the server im just handling the stream as a normal stream and write it using java io's Files.
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.