I'm trying to set up a program to record a portion of an internet audio stream, and save it to a file (preferably mp3 or wav). I've looked everywhere and I can't find any decent ways to do this. I found two different libraries that seemed like they'd work (NativeBass and Xuggle), but neither supported 64-bit windows which is what I need.
Does anyone know of any simple ways to save a portion of an internet audio stream using java? (If it's important, it's an "audio/mpeg" stream).
EDIT: Okay, I found a way that seems to work. But I still have a question
import java.net.URLConnection;
import java.net.URL;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
public class Test{
public static void main (String[] args){
try{
URLConnection conn = new URL("http://streamurl.com/example").openConnection();
InputStream is = conn.getInputStream();
OutputStream outstream = new FileOutputStream(new File("C:/Users/Me/Desktop/output.mp3"));
byte[] buffer = new byte[4096];
int len;
long t = System.currentTimeMillis();
while ((len = is.read(buffer)) > 0 && System.currentTimeMillis() - t <= 5000) {
outstream.write(buffer, 0, len);
}
outstream.close();
}
catch(Exception e){
System.out.print(e);
}
}
}
I got most of this from another answer on here after a bit more searching. However, one thing I'm trying to do is only record for a certain amount of time. As you can see above, I tried to only record a 5 second interval.
long t = System.currentTimeMillis();
while ((len = is.read(buffer)) > 0 && System.currentTimeMillis() - t <= 5000) {
However, for one reason or another, the recorded audio isn't 5 seconds long, it's 16. Does anyone know how to be more precise in limiting the length of the stream?
Create a DataLine.Info object to hold information of a data line. Obtain a TargetDataLine object which represents an input data line from which audio data can be captured, using the method getLineInfo(DataLine.Info) of the AudioSystem class. Open and start the target data line to begin capturing audio data.
An audio input stream is an input stream with a specified audio format and length. The length is expressed in sample frames, not bytes. Several methods are provided for reading a certain number of bytes from the stream, or an unspecified number of bytes.
The Java Sound API specification provides low-level support for audio operations such as audio playback and capture (recording), mixing, MIDI sequencing, and MIDI synthesis in an extensible, flexible framework.
If you exactly want 5 seconds you can calculate it yourself based on the number of bytes you have received and the bit rate of the audio stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With