File size: 2,447 Bytes
28b5ddf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.sound.sampled.*;
import org.json.JSONObject;

public class TextToSpeechClient {
    private final String apiKey;
    private final String model = "facebook/fastspeech2-en-ljspeech";

    public TextToSpeechClient(String apiKey) { 
        this.apiKey = apiKey;
    }

    public void speakText(String text) throws IOException {
        String inputJson = "{\n" +
                "  \"inputs\": \"" + text.replace("\"", "\\\"") + "\",\n" +
                "  \"parameters\": {\n" +
                "    \"return_timestamps\": false\n" +
                "  }\n" +
                "}";

        URL url = new URL("https://api-inference.huggingface.co/models/" + model);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + apiKey);
        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()) {
                // Save the audio to a temporary file
                File tempFile = File.createTempFile("speech", ".wav");
                try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, bytesRead);
                    }
                }

                // 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 the temporary file
                tempFile.delete();
            }
        } else {
            throw new IOException("Error: " + status);
        }
    }
}