7

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?

Kev
  • 118,037
  • 53
  • 300
  • 385
404 Not Found
  • 3,635
  • 2
  • 28
  • 34

1 Answers1

4

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.

Robert
  • 39,162
  • 17
  • 99
  • 152
  • I had already tried that, but after getting this comment, I reread the wikipedia article on data rates. Apparently I had read the wrong part of the article (kBps instead of kbps) which resulted in my confusion (since I was getting 66000 bytes / second instead of 8250 bytes/second). – 404 Not Found Dec 04 '10 at 19:08