view yetilab/stream/playback.yeti @ 219:ff97765b1d1b matrix_opaque_immutable

More block -> vector
author Chris Cannam
date Sat, 11 May 2013 12:07:21 +0100
parents a7f4eb1cdd72
children 937f908cae52
line wrap: on
line source

module yetilab.stream.playback;

vec = load yetilab.block.vector;
fr = load yetilab.stream.framer;
af = load yetilab.stream.audiofile;
ch = load yetilab.stream.channels;

import javax.sound.sampled:
    AudioSystem, AudioFormat, AudioFormat$Encoding, SourceDataLine;

import java.nio: ByteBuffer, ByteOrder;

playBlock line b is ~SourceDataLine -> 'a -> () =
   (len = vec.length b;
    samples = vec.primitive b;
    nb = len * 2;
    bytes = new byte[nb];
    bb = ByteBuffer#wrap(bytes, 0, nb);
    bb#order(ByteOrder#LITTLE_ENDIAN);
    sb = bb#asShortBuffer();
    for [0..len-1] do i: sb#put(i, samples[i] * 32767.0); () done;
    actual = line#write(bytes, 0, nb); 
    ());

play line blocks = for blocks (playBlock line);
    
open { rate, channels } = 
   (format = new AudioFormat(AudioFormat$Encoding#PCM_SIGNED, rate, 16,
                             channels, channels * 2, rate, false);
    line = AudioSystem#getSourceDataLine(format);
    line#open(format);
    line#start();
    {
        line,
        play = play line,
        channels = line#getFormat()#getChannels(),
        close () = (line#drain(); line#close()),
    });

playStream stream =
   (line = open { rate = stream.sampleRate, channels = stream.channels };
    blocksize = 10240;
    not stream.finished? loop
        line.play [(ch.mixedAndInterleavedTo line.channels 
                    (stream.read blocksize))];
    line.close();
    stream.close());

playFile filename = 
    playStream (af.open filename);

{
    open, play, playStream, playFile,
}