I'm trying to partially stream an mp3 file, but all the bytes before the requested "byte-mark" is stil being downloaded:
- Let's assume that the mp3 file is 7000000 bytes in filesize.
- I "jump" to 6000000 bytes and begin streaming from there to the end.
- But I notice that every byte from 1-5999999 is being downloaded before the mp3 file is being played from the 6000000 byte mark.
I am using JLayer (Java Zoom - http://www.javazoom.net/javalayer/javalayer.html) to play the mp3 file.
import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import javazoom.jl.decoder.JavaLayerException; import javazoom.jl.player.advanced.AdvancedPlayer; try { URL url = new URL("http://somerandomsite.com/audiotestfile.mp3"); URLConnection connection = url.openConnection(); connection.connect(); int fileSize = connection.getContentLength(); InputStream inputStream = url.openStream(); System.out.println("Filesize in bytes: " + fileSize); // Lets assume the filesize of the mp3 file is 7000000 bytes long skippedBytes = inputStream.skip(6000000); // Skip to 6000000 bytes to only stream the file partially System.out.println("Skipped bytes: " + skippedBytes); // The skipped bytes are equal to 6000000 bytes, but all previous bytes are still being downloaded. AdvancedPlayer ap = new AdvancedPlayer(inputStream); ap.play(); } catch (FileNotFoundException | JavaLayerException e) { System.out.println(e.getMessage()); }
How do I stream partially?
I think what you want to do is to have the server only send you from byte 6000000 onwards, but your code above is actually downloading the entire stream and simply ignoring or 'skipping' the first 6000000 bytes, as you have observed.
This is because the InputStream.skip essentially reads in and ignores the bytes you tell it to skip. From the documentation for InputStream skip:
What I think you actually want to do is to request from the server that it starts streaming to you from the 6000001'th byte in the mp3 file. One way to do this is to use a concept called 'Byte Serving':
There is an example of the message flow back and forth to there server in this answer - in this case it is for an mp4 file but the approach is exactly the same: https://stackoverflow.com/a/8507991/334402