Pu Zhibing
2025-04-25 20fb7c22fd9d4a936a2e9f4b003da51a0c2a0217
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
package com.stylefeng.guns.modular.system.util;
 
import com.google.cloud.texttospeech.v1.*;
import com.google.protobuf.ByteString;
 
import java.io.FileOutputStream;
import java.io.OutputStream;
 
/**
 * Google语音合成工具
 * @author zhibing.pu
 * @Date 2024/7/11 9:09
 */
public class TextToSpeechUtil {
    
    
    /**
     * 合成音频文件
     * @param languageCode  语言编号
     * @param text  合成文本
     * @param fileName  音频文件名称
     * @throws Exception
     */
    public static String create(String languageCode, String text, String fileName) throws Exception {
        // Instantiates a client
        try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
            // Set the text input to be synthesized
            SynthesisInput input = SynthesisInput.newBuilder().setText(text).build();
            
            // Build the voice request, select the language code ("en-US") and the ssml voice gender
            // ("neutral")
            VoiceSelectionParams voice =
                    VoiceSelectionParams.newBuilder()
                            .setLanguageCode(languageCode)
                            .setSsmlGender(SsmlVoiceGender.MALE)
                            .build();
            
            // Select the type of audio file you want returned
            AudioConfig audioConfig =
                    AudioConfig.newBuilder().setAudioEncoding(AudioEncoding.MP3).build();
            
            // Perform the text-to-speech request on the text input with the selected voice parameters and
            // audio file type
            SynthesizeSpeechResponse response =
                    textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
            
            // Get the audio contents from the response
            ByteString audioContents = response.getAudioContent();
            
            // Write the response to the output file.
            try (OutputStream out = new FileOutputStream("/home/igotechgh/nginx/html/files/audio/" + fileName)) {
                out.write(audioContents.toByteArray());
                return "https://igo.i-go.group/files/audio/" + fileName;
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }
    }
}