import java.io.*; public class ESpeakTTSClient { private Process currentProcess; public ESpeakTTSClient() { // Check if espeak is installed try { Process process = Runtime.getRuntime().exec("espeak --version"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String version = reader.readLine(); System.out.println("eSpeak version: " + version); int exitCode = process.waitFor(); if (exitCode != 0) { throw new RuntimeException("eSpeak is not installed. Please install it first."); } } catch (IOException | InterruptedException e) { throw new RuntimeException("Error checking eSpeak installation: " + e.getMessage()); } } public void speakText(String text) throws IOException { try { // Stop any existing speech stopSpeaking(); System.out.println("Attempting to speak text: " + text); // Use espeak to generate speech directly ProcessBuilder pb = new ProcessBuilder( "espeak", "-v", "en-gb", // British English voice "-s", "120", // Slower speed for clarity "-p", "50", // Medium pitch "-a", "100", // Full amplitude "-g", "5", // Word gap "-k", "5", // Emphasis text // Text to speak ); System.out.println("Starting eSpeak process..."); currentProcess = pb.start(); // Capture any error output BufferedReader errorReader = new BufferedReader(new InputStreamReader(currentProcess.getErrorStream())); String errorLine; while ((errorLine = errorReader.readLine()) != null) { System.err.println("eSpeak error: " + errorLine); } int exitCode = currentProcess.waitFor(); System.out.println("eSpeak process completed with exit code: " + exitCode); if (exitCode != 0) { System.err.println("Error generating speech with exit code: " + exitCode); throw new IOException("Error generating speech: " + exitCode); } } catch (InterruptedException e) { System.err.println("Speech generation interrupted: " + e.getMessage()); throw new IOException("Speech generation interrupted: " + e.getMessage()); } } public void stopSpeaking() { if (currentProcess != null && currentProcess.isAlive()) { currentProcess.destroy(); try { currentProcess.waitFor(); } catch (InterruptedException e) { System.err.println("Error stopping speech: " + e.getMessage()); } currentProcess = null; } } }