package org.wikiwebserver.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.sound.sampled.AudioFileFormat;

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

public class SpeechHelper {
    
    public static final int MAX_CHARS_TO_SPEAK = 2048;
    
    private static SpeechHelper speech = null;
    
    private Voice voice = null;
    
    public static synchronized SpeechHelper getInstance() {
        if (speech == null) {
            speech = new SpeechHelper();
        }
        return speech;
    }
    
    private SpeechHelper() {
        VoiceManager voiceManager = VoiceManager.getInstance();
        voice = voiceManager.getVoice("kevin16");   
        voice.allocate();
    }
    
    public synchronized byte[] getSoundData(String text, AudioFileFormat.Type type) throws IOException {
        
        if (text == null || text.length() == 0) {
            text = "There is nothing to reed";            
        }
        
        if (text.length() > MAX_CHARS_TO_SPEAK) {
            text = text.substring(0, MAX_CHARS_TO_SPEAK)
                 + ".  Sorry I am bored of reading this. It is too long";
        }
        
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        AudioPlayerStreamer player = new AudioPlayerStreamer(out, type);

        voice.setAudioPlayer(player);          
        voice.speak(text);
        player.close();
        voice.setAudioPlayer(null); // Free up for garbage collection
        
        //voice.deallocate();
        
        return out.toByteArray();
    }
}
