/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package turgen.generator;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.SourceDataLine;
import turgen.Utils;


public class AudioSignalWriter implements SignalWriter {

    protected SourceDataLine line;
    protected final AudioFormat audioFormat;
    protected final int bufferSize;
    
    
    public AudioSignalWriter(int bitsPerSample,int channels,boolean signed,int bufferSize) {
        this.bufferSize=bufferSize;
        audioFormat = new AudioFormat((float) 44100, bitsPerSample, channels, signed, false);
    }
    
    
    public String prepare(String outputFile ) {
        /*Try to initialize sound card*/
        try {
            
            Line.Info desiredInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
            line = (SourceDataLine) AudioSystem.getLine(desiredInfo);
            line.open(audioFormat, bufferSize);
            line.start();
            
        } catch (Exception e) {
            return Utils.getTitledExceptionMessage("Unable to initialize audio system",e);
        }
        
        return null;
    }

    public void writeInitialSignal(byte[] signal) throws Exception {
        write(signal);
    }

    public void writeTerminationSignal(byte[] signal) throws Exception {
        /*Nothing to be here*/
    }

    public void write(byte[] signal) throws Exception {
        line.write(signal, 0, signal.length);
    }

    public void prepareForClose() throws Exception {
        line.drain();
        line.stop();
    }

    public void close() throws Exception {
        line.close();
    }

}
