Search code examples
javaandroidaudioaudio-streamingaudio-recording

Downloading online audio stream and saving it in parts


I'm trying to download a audio stream and save it in parts of 250kb. I got it working by downloading the audio file, closing the connection and start a new download at 250kb. However when I do it this way I'm missing about 10 seconds of audio between the audio files.

The code I'm using to download the audio stream in parts of 250kb is:

public void downloadMP3() {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {

                URL url = new URL("http://icecast.omroep.nl/3fm-bb-aac");
                InputStream inputStream = url.openStream();
                File filemp3 = new File(
                        Environment.getExternalStorageDirectory() + "/radiorecordings/file" + fileCount + ".mp4a");
                FileOutputStream fileOutputStream = new FileOutputStream(filemp3);

                int c;
                int bytesRead = 0;

                //keep reading until file is 250kb (250.000 bytes)
                while ((c = inputStream.read()) != -1 && bytesRead < 250000) {
                    Log.d("...", "bytesRead=" + bytesRead);
                    fileOutputStream.write(c);
                    bytesRead++;
                }

                fileCount++;
                downloadMP3();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

I know using the Thread is not the best solution, but that's not what this is about. Is there any reason why the fragments do not fit perfectly to each other?


Solution

  • The gap between audio parts is probably due to the connection being closed and reopened.

    Why don't you keep the connection open all the time, and use a buffered output stream to write to a file? You could write your own output stream (by extending the regular buffered one) and have it write to a file. Once it reaches 250kb, it could decide to close that file and reopen a new one, buffering audio to memory in the meantime.