AIProject / GoogleTTSClient.java
Saahil-doryu's picture
Upload 18 files
28b5ddf verified
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.sound.sampled.*;
import org.json.JSONObject;
public class GoogleTTSClient {
private final String apiKey;
private final String voiceName = "en-US-Neural2-F"; // Female voice
private final String languageCode = "en-US";
public GoogleTTSClient(String apiKey) {
this.apiKey = apiKey;
}
public void speakText(String text) throws IOException {
String inputJson = "{\n" +
" \"input\": {\n" +
" \"text\": \"" + text.replace("\"", "\\\"") + "\"\n" +
" },\n" +
" \"voice\": {\n" +
" \"languageCode\": \"" + languageCode + "\",\n" +
" \"name\": \"" + voiceName + "\"\n" +
" },\n" +
" \"audioConfig\": {\n" +
" \"audioEncoding\": \"LINEAR16\",\n" +
" \"speakingRate\": 1.0,\n" +
" \"pitch\": 0.0\n" +
" }\n" +
"}";
URL url = new URL("https://texttospeech.googleapis.com/v1/text:synthesize?key=" + apiKey);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(inputJson.getBytes("utf-8"));
}
int status = conn.getResponseCode();
if (status == 200) {
try (InputStream is = conn.getInputStream()) {
// Parse the response
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
JSONObject jsonResponse = new JSONObject(response.toString());
String audioContent = jsonResponse.getString("audioContent");
// Decode base64 audio content
byte[] audioBytes = java.util.Base64.getDecoder().decode(audioContent);
// Save to temporary file
File tempFile = File.createTempFile("speech", ".wav");
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
fos.write(audioBytes);
}
// Play the audio
try (AudioInputStream audioIn = AudioSystem.getAudioInputStream(tempFile)) {
Clip clip = AudioSystem.getClip();
clip.open(audioIn);
clip.start();
clip.drain();
clip.close();
} catch (UnsupportedAudioFileException | LineUnavailableException e) {
throw new IOException("Error playing audio: " + e.getMessage());
}
// Clean up
tempFile.delete();
}
} else {
throw new IOException("Error: " + status);
}
}
}