Java Code Examples for javax.sound.sampled.AudioInputStream#read()

The following examples show how to use javax.sound.sampled.AudioInputStream#read() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SkipTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    AudioFloatFormatConverter converter = new AudioFloatFormatConverter();
    byte[] data = { 10, 20, 30, 40, 30, 20, 10 };
    AudioFormat format = new AudioFormat(8000, 8, 1, true, false);
    AudioFormat format2 = new AudioFormat(16000, 8, 1, true, false);
    AudioInputStream ais = new AudioInputStream(new ByteArrayInputStream(
            data), format, data.length);
    AudioInputStream ais2 = converter.getAudioInputStream(format2, ais);
    byte[] data2 = new byte[30];
    int ret = ais2.read(data2, 0, data2.length);
    ais.reset();
    AudioInputStream ais3 = converter.getAudioInputStream(format2, ais);
    byte[] data3 = new byte[100];
    ais3.skip(7);
    int ret2 = ais3.read(data3, 7, data3.length);
    if (ret2 != ret - 7)
        throw new Exception("Skip doesn't work correctly (" + ret2 + " != "
                + (ret - 7) + ")");
    for (int i = 7; i < ret2 + 7; i++) {
        if (data3[i] != data2[i])
            throw new Exception("Skip doesn't work correctly (" + data3[i]
                    + " != " + data2[i] + ")");
    }
}
 
Example 2
Source File: SoftAudioPusher.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    byte[] buffer = SoftAudioPusher.this.buffer;
    AudioInputStream ais = SoftAudioPusher.this.ais;
    SourceDataLine sourceDataLine = SoftAudioPusher.this.sourceDataLine;

    try {
        while (active) {
            // Read from audio source
            int count = ais.read(buffer);
            if(count < 0) break;
            // Write byte buffer to source output
            sourceDataLine.write(buffer, 0, count);
        }
    } catch (IOException e) {
        active = false;
        //e.printStackTrace();
    }

}
 
Example 3
Source File: JavaSoundAudioClip.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void readStream(AudioInputStream as, long byteLen) throws IOException {
    // arrays "only" max. 2GB
    int intLen;
    if (byteLen > 2147483647) {
        intLen = 2147483647;
    } else {
        intLen = (int) byteLen;
    }
    loadedAudio = new byte[intLen];
    loadedAudioByteLength = 0;

    // this loop may throw an IOException
    while (true) {
        int bytesRead = as.read(loadedAudio, loadedAudioByteLength, intLen - loadedAudioByteLength);
        if (bytesRead <= 0) {
            as.close();
            break;
        }
        loadedAudioByteLength += bytesRead;
    }
}
 
Example 4
Source File: AlawEncoderSync.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    log("ConversionThread[" + num + "] started.");
    try {
        InputStream inStream = new ByteArrayInputStream(pcmBuffer);

        AudioInputStream pcmStream = new AudioInputStream(
                inStream, pcmFormat, AudioSystem.NOT_SPECIFIED);
        AudioInputStream alawStream = AudioSystem.getAudioInputStream(alawFormat, pcmStream);

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        int read = 0;
        byte[] data = new byte[4096];
        while((read = alawStream.read(data)) != -1) {
            outStream.write(data, 0, read);
       }
       alawStream.close();
       resultArray = outStream.toByteArray();
    } catch (Exception ex) {
        log("ConversionThread[" + num + "] exception:");
        log(ex);
    }
    log("ConversionThread[" + num + "] completed.");
}
 
Example 5
Source File: WaveFloatFileWriter.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public void write(AudioInputStream stream, RIFFWriter writer)
        throws IOException {

    RIFFWriter fmt_chunk = writer.writeChunk("fmt ");

    AudioFormat format = stream.getFormat();
    fmt_chunk.writeUnsignedShort(3); // WAVE_FORMAT_IEEE_FLOAT
    fmt_chunk.writeUnsignedShort(format.getChannels());
    fmt_chunk.writeUnsignedInt((int) format.getSampleRate());
    fmt_chunk.writeUnsignedInt(((int) format.getFrameRate())
            * format.getFrameSize());
    fmt_chunk.writeUnsignedShort(format.getFrameSize());
    fmt_chunk.writeUnsignedShort(format.getSampleSizeInBits());
    fmt_chunk.close();
    RIFFWriter data_chunk = writer.writeChunk("data");
    byte[] buff = new byte[1024];
    int len;
    while ((len = stream.read(buff, 0, buff.length)) != -1)
        data_chunk.write(buff, 0, len);
    data_chunk.close();
}
 
Example 6
Source File: Sample.java    From mpcmaid with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Sample open(final AudioInputStream audioStream) throws LineUnavailableException, IOException {
	final int frameLength = (int) audioStream.getFrameLength();
	if (frameLength > 44100 * 8 * 2) {
		throw new IllegalArgumentException("The audio file is too long (must be shorter than 4 bars at 50BPM)");
	}
	final AudioFormat format = audioStream.getFormat();
	final int frameSize = (int) format.getFrameSize();
	final byte[] bytes = new byte[frameLength * frameSize];
	final int result = audioStream.read(bytes);
	if (result < 0) {
		return null;
	}

	audioStream.close();

	return new Sample(bytes, format, frameLength);
}
 
Example 7
Source File: SkipTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    AudioFloatFormatConverter converter = new AudioFloatFormatConverter();
    byte[] data = { 10, 20, 30, 40, 30, 20, 10 };
    AudioFormat format = new AudioFormat(8000, 8, 1, true, false);
    AudioFormat format2 = new AudioFormat(16000, 8, 1, true, false);
    AudioInputStream ais = new AudioInputStream(new ByteArrayInputStream(
            data), format, data.length);
    AudioInputStream ais2 = converter.getAudioInputStream(format2, ais);
    byte[] data2 = new byte[30];
    int ret = ais2.read(data2, 0, data2.length);
    ais.reset();
    AudioInputStream ais3 = converter.getAudioInputStream(format2, ais);
    byte[] data3 = new byte[100];
    ais3.skip(7);
    int ret2 = ais3.read(data3, 7, data3.length);
    if (ret2 != ret - 7)
        throw new Exception("Skip doesn't work correctly (" + ret2 + " != "
                + (ret - 7) + ")");
    for (int i = 7; i < ret2 + 7; i++) {
        if (data3[i] != data2[i])
            throw new Exception("Skip doesn't work correctly (" + data3[i]
                    + " != " + data2[i] + ")");
    }
}
 
Example 8
Source File: JavaSoundAudioClip.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private void readStream(AudioInputStream as) throws IOException {

        DirectBAOS baos = new DirectBAOS();
        byte[] buffer = new byte[16384];
        int bytesRead = 0;
        int totalBytesRead = 0;

        // this loop may throw an IOException
        while( true ) {
            bytesRead = as.read(buffer, 0, buffer.length);
            if (bytesRead <= 0) {
                as.close();
                break;
            }
            totalBytesRead += bytesRead;
            baos.write(buffer, 0, bytesRead);
        }
        loadedAudio = baos.getInternalBuffer();
        loadedAudioByteLength = totalBytesRead;
    }
 
Example 9
Source File: WaveFloatFileWriter.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public void write(AudioInputStream stream, RIFFWriter writer)
        throws IOException {

    RIFFWriter fmt_chunk = writer.writeChunk("fmt ");

    AudioFormat format = stream.getFormat();
    fmt_chunk.writeUnsignedShort(3); // WAVE_FORMAT_IEEE_FLOAT
    fmt_chunk.writeUnsignedShort(format.getChannels());
    fmt_chunk.writeUnsignedInt((int) format.getSampleRate());
    fmt_chunk.writeUnsignedInt(((int) format.getFrameRate())
            * format.getFrameSize());
    fmt_chunk.writeUnsignedShort(format.getFrameSize());
    fmt_chunk.writeUnsignedShort(format.getSampleSizeInBits());
    fmt_chunk.close();
    RIFFWriter data_chunk = writer.writeChunk("data");
    byte[] buff = new byte[1024];
    int len;
    while ((len = stream.read(buff, 0, buff.length)) != -1)
        data_chunk.write(buff, 0, len);
    data_chunk.close();
}
 
Example 10
Source File: SoftAudioPusher.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    byte[] buffer = SoftAudioPusher.this.buffer;
    AudioInputStream ais = SoftAudioPusher.this.ais;
    SourceDataLine sourceDataLine = SoftAudioPusher.this.sourceDataLine;

    try {
        while (active) {
            // Read from audio source
            int count = ais.read(buffer);
            if(count < 0) break;
            // Write byte buffer to source output
            sourceDataLine.write(buffer, 0, count);
        }
    } catch (IOException e) {
        active = false;
        //e.printStackTrace();
    }

}
 
Example 11
Source File: JavaSoundAudioClip.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void readStream(AudioInputStream as, long byteLen) throws IOException {
    // arrays "only" max. 2GB
    int intLen;
    if (byteLen > 2147483647) {
        intLen = 2147483647;
    } else {
        intLen = (int) byteLen;
    }
    loadedAudio = new byte[intLen];
    loadedAudioByteLength = 0;

    // this loop may throw an IOException
    while (true) {
        int bytesRead = as.read(loadedAudio, loadedAudioByteLength, intLen - loadedAudioByteLength);
        if (bytesRead <= 0) {
            as.close();
            break;
        }
        loadedAudioByteLength += bytesRead;
    }
}
 
Example 12
Source File: AudioFileSoundbankReader.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public Soundbank getSoundbank(AudioInputStream ais)
        throws InvalidMidiDataException, IOException {
    try {
        byte[] buffer;
        if (ais.getFrameLength() == -1) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buff = new byte[1024
                    - (1024 % ais.getFormat().getFrameSize())];
            int ret;
            while ((ret = ais.read(buff)) != -1) {
                baos.write(buff, 0, ret);
            }
            ais.close();
            buffer = baos.toByteArray();
        } else {
            buffer = new byte[(int) (ais.getFrameLength()
                                * ais.getFormat().getFrameSize())];
            new DataInputStream(ais).readFully(buffer);
        }
        ModelByteBufferWavetable osc = new ModelByteBufferWavetable(
                new ModelByteBuffer(buffer), ais.getFormat(), -4800);
        ModelPerformer performer = new ModelPerformer();
        performer.getOscillators().add(osc);

        SimpleSoundbank sbk = new SimpleSoundbank();
        SimpleInstrument ins = new SimpleInstrument();
        ins.add(performer);
        sbk.addInstrument(ins);
        return sbk;
    } catch (Exception e) {
        return null;
    }
}
 
Example 13
Source File: SoftMixingClip.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void open(AudioInputStream stream) throws LineUnavailableException,
        IOException {
    if (isOpen()) {
        throw new IllegalStateException("Clip is already open with format "
                + getFormat() + " and frame lengh of " + getFrameLength());
    }
    if (AudioFloatConverter.getConverter(stream.getFormat()) == null)
        throw new IllegalArgumentException("Invalid format : "
                + stream.getFormat().toString());

    if (stream.getFrameLength() != AudioSystem.NOT_SPECIFIED) {
        byte[] data = new byte[(int) stream.getFrameLength()
                * stream.getFormat().getFrameSize()];
        int readsize = 512 * stream.getFormat().getFrameSize();
        int len = 0;
        while (len != data.length) {
            if (readsize > data.length - len)
                readsize = data.length - len;
            int ret = stream.read(data, len, readsize);
            if (ret == -1)
                break;
            if (ret == 0)
                Thread.yield();
            len += ret;
        }
        open(stream.getFormat(), data, 0, len);
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[512 * stream.getFormat().getFrameSize()];
        int r = 0;
        while ((r = stream.read(b)) != -1) {
            if (r == 0)
                Thread.yield();
            baos.write(b, 0, r);
        }
        open(stream.getFormat(), baos.toByteArray(), 0, baos.size());
    }

}
 
Example 14
Source File: AudioFileSoundbankReader.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public Soundbank getSoundbank(AudioInputStream ais)
        throws InvalidMidiDataException, IOException {
    try {
        byte[] buffer;
        if (ais.getFrameLength() == -1) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buff = new byte[1024
                    - (1024 % ais.getFormat().getFrameSize())];
            int ret;
            while ((ret = ais.read(buff)) != -1) {
                baos.write(buff, 0, ret);
            }
            ais.close();
            buffer = baos.toByteArray();
        } else {
            buffer = new byte[(int) (ais.getFrameLength()
                                * ais.getFormat().getFrameSize())];
            new DataInputStream(ais).readFully(buffer);
        }
        ModelByteBufferWavetable osc = new ModelByteBufferWavetable(
                new ModelByteBuffer(buffer), ais.getFormat(), -4800);
        ModelPerformer performer = new ModelPerformer();
        performer.getOscillators().add(osc);

        SimpleSoundbank sbk = new SimpleSoundbank();
        SimpleInstrument ins = new SimpleInstrument();
        ins.add(performer);
        sbk.addInstrument(ins);
        return sbk;
    } catch (Exception e) {
        return null;
    }
}
 
Example 15
Source File: SoftMixingClip.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void open(AudioInputStream stream) throws LineUnavailableException,
        IOException {
    if (isOpen()) {
        throw new IllegalStateException("Clip is already open with format "
                + getFormat() + " and frame lengh of " + getFrameLength());
    }
    if (AudioFloatConverter.getConverter(stream.getFormat()) == null)
        throw new IllegalArgumentException("Invalid format : "
                + stream.getFormat().toString());

    if (stream.getFrameLength() != AudioSystem.NOT_SPECIFIED) {
        byte[] data = new byte[(int) stream.getFrameLength()
                * stream.getFormat().getFrameSize()];
        int readsize = 512 * stream.getFormat().getFrameSize();
        int len = 0;
        while (len != data.length) {
            if (readsize > data.length - len)
                readsize = data.length - len;
            int ret = stream.read(data, len, readsize);
            if (ret == -1)
                break;
            if (ret == 0)
                Thread.yield();
            len += ret;
        }
        open(stream.getFormat(), data, 0, len);
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[512 * stream.getFormat().getFrameSize()];
        int r = 0;
        while ((r = stream.read(b)) != -1) {
            if (r == 0)
                Thread.yield();
            baos.write(b, 0, r);
        }
        open(stream.getFormat(), baos.toByteArray(), 0, baos.size());
    }

}
 
Example 16
Source File: TestPreciseTimestampRendering.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void test(Soundbank soundbank) throws Exception {

        // Create instance of synthesizer using the testing soundbank above
        AudioSynthesizer synth = new SoftSynthesizer();
        AudioInputStream stream = synth.openStream(format, null);
        synth.unloadAllInstruments(synth.getDefaultSoundbank());
        synth.loadAllInstruments(soundbank);
        Receiver recv = synth.getReceiver();

        // Set volume to max and turn reverb off
        ShortMessage reverb_off = new ShortMessage();
        reverb_off.setMessage(ShortMessage.CONTROL_CHANGE, 91, 0);
        recv.send(reverb_off, -1);
        ShortMessage full_volume = new ShortMessage();
        full_volume.setMessage(ShortMessage.CONTROL_CHANGE, 7, 127);
        recv.send(full_volume, -1);

        Random random = new Random(3485934583945l);

        // Create random timestamps
        long[] test_timestamps = new long[30];
        for (int i = 1; i < test_timestamps.length; i++) {
            test_timestamps[i] = i * 44100
                    + (int) (random.nextDouble() * 22050.0);
        }

        // Send midi note on message to synthesizer
        for (int i = 0; i < test_timestamps.length; i++) {
            ShortMessage midi_on = new ShortMessage();
            midi_on.setMessage(ShortMessage.NOTE_ON, 69, 127);
            recv.send(midi_on,
                    (long) ((test_timestamps[i] / 44100.0) * 1000000.0));
        }

        // Measure timing from rendered audio
        float[] fbuffer = new float[100];
        byte[] buffer = new byte[fbuffer.length * format.getFrameSize()];
        long firsts = -1;
        int counter = 0;
        long s = 0;
        long max_jitter = 0;
        outerloop: for (int k = 0; k < 10000000; k++) {
            stream.read(buffer);
            AudioFloatConverter.getConverter(format).toFloatArray(buffer,
                    fbuffer);
            for (int i = 0; i < fbuffer.length; i++) {
                if (fbuffer[i] != 0) {
                    if (firsts == -1)
                        firsts = s;

                    long measure_time = (s - firsts);
                    long predicted_time = test_timestamps[counter];

                    long jitter = Math.abs(measure_time - predicted_time);

                    if (jitter > 10)
                        max_jitter = jitter;

                    counter++;
                    if (counter == test_timestamps.length)
                        break outerloop;
                }
                s++;
            }
        }
        synth.close();

        if (counter == 0)
            throw new Exception("Nothing was measured!");

        if (max_jitter != 0) {
            throw new Exception("Jitter has occurred! "
                    + "(max jitter = " + max_jitter + ")");
        }

    }
 
Example 17
Source File: TestPreciseTimestampRendering.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void test(Soundbank soundbank) throws Exception {

        // Create instance of synthesizer using the testing soundbank above
        AudioSynthesizer synth = new SoftSynthesizer();
        AudioInputStream stream = synth.openStream(format, null);
        synth.unloadAllInstruments(synth.getDefaultSoundbank());
        synth.loadAllInstruments(soundbank);
        Receiver recv = synth.getReceiver();

        // Set volume to max and turn reverb off
        ShortMessage reverb_off = new ShortMessage();
        reverb_off.setMessage(ShortMessage.CONTROL_CHANGE, 91, 0);
        recv.send(reverb_off, -1);
        ShortMessage full_volume = new ShortMessage();
        full_volume.setMessage(ShortMessage.CONTROL_CHANGE, 7, 127);
        recv.send(full_volume, -1);

        Random random = new Random(3485934583945l);

        // Create random timestamps
        long[] test_timestamps = new long[30];
        for (int i = 1; i < test_timestamps.length; i++) {
            test_timestamps[i] = i * 44100
                    + (int) (random.nextDouble() * 22050.0);
        }

        // Send midi note on message to synthesizer
        for (int i = 0; i < test_timestamps.length; i++) {
            ShortMessage midi_on = new ShortMessage();
            midi_on.setMessage(ShortMessage.NOTE_ON, 69, 127);
            recv.send(midi_on,
                    (long) ((test_timestamps[i] / 44100.0) * 1000000.0));
        }

        // Measure timing from rendered audio
        float[] fbuffer = new float[100];
        byte[] buffer = new byte[fbuffer.length * format.getFrameSize()];
        long firsts = -1;
        int counter = 0;
        long s = 0;
        long max_jitter = 0;
        outerloop: for (int k = 0; k < 10000000; k++) {
            stream.read(buffer);
            AudioFloatConverter.getConverter(format).toFloatArray(buffer,
                    fbuffer);
            for (int i = 0; i < fbuffer.length; i++) {
                if (fbuffer[i] != 0) {
                    if (firsts == -1)
                        firsts = s;

                    long measure_time = (s - firsts);
                    long predicted_time = test_timestamps[counter];

                    long jitter = Math.abs(measure_time - predicted_time);

                    if (jitter > 10)
                        max_jitter = jitter;

                    counter++;
                    if (counter == test_timestamps.length)
                        break outerloop;
                }
                s++;
            }
        }
        synth.close();

        if (counter == 0)
            throw new Exception("Nothing was measured!");

        if (max_jitter != 0) {
            throw new Exception("Jitter has occurred! "
                    + "(max jitter = " + max_jitter + ")");
        }

    }
 
Example 18
Source File: SoftSynthesizer.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public int read(byte[] b, int off, int len) throws IOException {
     AudioInputStream local_stream = stream;
     if(local_stream != null)
         return local_stream.read(b, off, len);
     else
     {
         int flen = len / samplesize;
         if(silentbuffer == null || silentbuffer.length < flen)
             silentbuffer = new float[flen];
         converter.toByteArray(silentbuffer, flen, b, off);

         silent_samples += (long)((len / framesize));

         if(pusher != null)
         if(weak_stream_link.get() == null)
         {
             Runnable runnable = new Runnable()
             {
                 SoftAudioPusher _pusher = pusher;
                 AudioInputStream _jitter_stream = jitter_stream;
                 SourceDataLine _sourceDataLine = sourceDataLine;
                 public void run()
                 {
                     _pusher.stop();
                     if(_jitter_stream != null)
                        try {
                            _jitter_stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                     if(_sourceDataLine != null)
                         _sourceDataLine.close();
                 }
             };
             pusher = null;
             jitter_stream = null;
             sourceDataLine = null;
             new Thread(runnable).start();
         }
         return len;
     }
}
 
Example 19
Source File: TestPreciseTimestampRendering.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void test(Soundbank soundbank) throws Exception {

        // Create instance of synthesizer using the testing soundbank above
        AudioSynthesizer synth = new SoftSynthesizer();
        AudioInputStream stream = synth.openStream(format, null);
        synth.unloadAllInstruments(synth.getDefaultSoundbank());
        synth.loadAllInstruments(soundbank);
        Receiver recv = synth.getReceiver();

        // Set volume to max and turn reverb off
        ShortMessage reverb_off = new ShortMessage();
        reverb_off.setMessage(ShortMessage.CONTROL_CHANGE, 91, 0);
        recv.send(reverb_off, -1);
        ShortMessage full_volume = new ShortMessage();
        full_volume.setMessage(ShortMessage.CONTROL_CHANGE, 7, 127);
        recv.send(full_volume, -1);

        Random random = new Random(3485934583945l);

        // Create random timestamps
        long[] test_timestamps = new long[30];
        for (int i = 1; i < test_timestamps.length; i++) {
            test_timestamps[i] = i * 44100
                    + (int) (random.nextDouble() * 22050.0);
        }

        // Send midi note on message to synthesizer
        for (int i = 0; i < test_timestamps.length; i++) {
            ShortMessage midi_on = new ShortMessage();
            midi_on.setMessage(ShortMessage.NOTE_ON, 69, 127);
            recv.send(midi_on,
                    (long) ((test_timestamps[i] / 44100.0) * 1000000.0));
        }

        // Measure timing from rendered audio
        float[] fbuffer = new float[100];
        byte[] buffer = new byte[fbuffer.length * format.getFrameSize()];
        long firsts = -1;
        int counter = 0;
        long s = 0;
        long max_jitter = 0;
        outerloop: for (int k = 0; k < 10000000; k++) {
            stream.read(buffer);
            AudioFloatConverter.getConverter(format).toFloatArray(buffer,
                    fbuffer);
            for (int i = 0; i < fbuffer.length; i++) {
                if (fbuffer[i] != 0) {
                    if (firsts == -1)
                        firsts = s;

                    long measure_time = (s - firsts);
                    long predicted_time = test_timestamps[counter];

                    long jitter = Math.abs(measure_time - predicted_time);

                    if (jitter > 10)
                        max_jitter = jitter;

                    counter++;
                    if (counter == test_timestamps.length)
                        break outerloop;
                }
                s++;
            }
        }
        synth.close();

        if (counter == 0)
            throw new Exception("Nothing was measured!");

        if (max_jitter != 0) {
            throw new Exception("Jitter has occurred! "
                    + "(max jitter = " + max_jitter + ")");
        }

    }
 
Example 20
Source File: TestPreciseTimestampRendering.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void test(Soundbank soundbank) throws Exception {

        // Create instance of synthesizer using the testing soundbank above
        AudioSynthesizer synth = new SoftSynthesizer();
        AudioInputStream stream = synth.openStream(format, null);
        synth.unloadAllInstruments(synth.getDefaultSoundbank());
        synth.loadAllInstruments(soundbank);
        Receiver recv = synth.getReceiver();

        // Set volume to max and turn reverb off
        ShortMessage reverb_off = new ShortMessage();
        reverb_off.setMessage(ShortMessage.CONTROL_CHANGE, 91, 0);
        recv.send(reverb_off, -1);
        ShortMessage full_volume = new ShortMessage();
        full_volume.setMessage(ShortMessage.CONTROL_CHANGE, 7, 127);
        recv.send(full_volume, -1);

        Random random = new Random(3485934583945l);

        // Create random timestamps
        long[] test_timestamps = new long[30];
        for (int i = 1; i < test_timestamps.length; i++) {
            test_timestamps[i] = i * 44100
                    + (int) (random.nextDouble() * 22050.0);
        }

        // Send midi note on message to synthesizer
        for (int i = 0; i < test_timestamps.length; i++) {
            ShortMessage midi_on = new ShortMessage();
            midi_on.setMessage(ShortMessage.NOTE_ON, 69, 127);
            recv.send(midi_on,
                    (long) ((test_timestamps[i] / 44100.0) * 1000000.0));
        }

        // Measure timing from rendered audio
        float[] fbuffer = new float[100];
        byte[] buffer = new byte[fbuffer.length * format.getFrameSize()];
        long firsts = -1;
        int counter = 0;
        long s = 0;
        long max_jitter = 0;
        outerloop: for (int k = 0; k < 10000000; k++) {
            stream.read(buffer);
            AudioFloatConverter.getConverter(format).toFloatArray(buffer,
                    fbuffer);
            for (int i = 0; i < fbuffer.length; i++) {
                if (fbuffer[i] != 0) {
                    if (firsts == -1)
                        firsts = s;

                    long measure_time = (s - firsts);
                    long predicted_time = test_timestamps[counter];

                    long jitter = Math.abs(measure_time - predicted_time);

                    if (jitter > 10)
                        max_jitter = jitter;

                    counter++;
                    if (counter == test_timestamps.length)
                        break outerloop;
                }
                s++;
            }
        }
        synth.close();

        if (counter == 0)
            throw new Exception("Nothing was measured!");

        if (max_jitter != 0) {
            throw new Exception("Jitter has occurred! "
                    + "(max jitter = " + max_jitter + ")");
        }

    }