finnkuusisto / TinySound

Simple library for playing sounds and music in Java
http://finnkuusisto.github.com/TinySound
BSD 2-Clause "Simplified" License
99 stars 26 forks source link

Support streaming audio #11

Closed finnkuusisto closed 11 years ago

finnkuusisto commented 12 years ago

TinySound can take up a lot of memory when loading long sound files. It would be nice to write loaded audio data to a file in a temp directory and stream from there instead of keeping everything in memory.

finnkuusisto commented 12 years ago

This should probably be accomplished by making Sound and Music into interfaces and then having two implementations each. The default implementation could load data into memory as it does now and another implementation would stream from temp files that just contain the converted bytes. The streaming implementation could then just hang onto a URL for that temp file and create an AudioInputStream from an InputStream opened on the URL anytime that the audio needs to start from the beginning. Below is an example of how easy it is to get a URL and InputStreams for a temp file:

public static void main(String[] args) throws IOException {
    File tmp = File.createTempFile("derp", "derp");
    tmp.deleteOnExit();
    PrintStream out = new PrintStream(tmp);
    out.println("hello");
    out.println("world");
    out.close();
    URL url = tmp.toURI().toURL();
    System.out.println(url);

    byte[] data = new byte[10];
    InputStream in1 = url.openStream();
    in1.read(data);
    System.out.println(new String(data));

    data = new byte[10];
    InputStream in2 = url.openStream();
    in2.read(data);
    System.out.println(new String(data));

    AudioFormat FORMAT = new AudioFormat(
            AudioFormat.Encoding.PCM_SIGNED, //linear signed PCM
            44100, //44.1kHz sampling rate
            16, //16-bit
            2, //2 channels fool
            4, //frame size 4 bytes (16-bit, 2 channel)
            44100, //same as sampling rate
            false //little-endian
        );
    AudioInputStream ais = new AudioInputStream(url.openStream(), FORMAT,
            3);
    System.out.println(ais);
}
finnkuusisto commented 12 years ago

Progress is on branch streams_and_redesign.

finnkuusisto commented 11 years ago

This branch was merged.