package com.stylefeng.guns.modular.system.controller.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("/usr/local/nginx/html/files/audio/" + fileName)) {
|
out.write(audioContents.toByteArray());
|
return "http://182.160.16.251:81/files/audio/" + fileName;
|
}catch (Exception e){
|
e.printStackTrace();
|
}
|
return null;
|
}
|
}
|
}
|