Sunday, February 6, 2011

Text To Speech using Java API - Voice


In my previous Text To Speech post  , I talked about java speech API, FreeTTS and sample code for converting text to speech.
In this post , I am going to give an alternative way to achieve the same using FreeTTS.


There are a number of objects that work together to perform speech synthesis. One of them is voice.
The Voice is the central processing point for FreeTTS. The Voice takes as input a FreeTTSSpeakable, translates the text associated with the FreeTTSSpeakable into speech and generates audio output corresponding to that speech. Read more

The VoiceManager is the central repository of voices available to FreeTTS. You can use this sample code to get available voice list.

package com.sarf.tts;

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

public class VoiceDetector {
    public static void main(String[] args) {
     VoiceManager voiceManager;
     voiceManager = VoiceManager.getInstance();
     // Get all available voices
     Voice[] voices = voiceManager.getVoices();
     for (int i = 0; i < voices.length; i++) {
       System.out.println(voices[i].getName());
     }
   }
}

File Reader

This java class demonstrate the capability of java speech to read a text file loudly.
package com.sarf.tts;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

public class FileSpeaker {
  public static void main(String[] args) throws Exception {
     // Voice Name
     String voiceName = "kevin";
     VoiceManager voiceManager = null;
     Voice voice = null;

     voiceManager = VoiceManager.getInstance();
     voice = voiceManager.getVoice(voiceName);

     voice.setPitch((float) 4.00);
     voice.setPitchShift((float) .005);
     voice.setPitchRange((float) 0.01);
     // "business", "casual", "robotic", "breathy"
     voice.setStyle("business");
           
     //allocate the resources for the voice
     voice.allocate();

     // Create input stream from file
     InputStream in = new FileInputStream(new File("D:/temp/sample.txt"));
     voice.speak(in);

     voice.deallocate();
   }
} 
A wise old owl sat on an oak; The more he saw the less he spoke; The less he spoke the more he heard; Why aren't we like that wise old bird?