我希望输入文本来与计算机的扬声器将文本的内容再现为合成语音。我正在开发的应用程序是Java语言,为了获得理想的结果,我使用了Google测试语音库。我从以下代码开始: https://cloud.google.com/text-to-speech/docs/reference/libraries
但是您可以看到语音消息已保存在文件中,而不与扬声器重现。因此,我的问题是如何与运行该应用程序的计算机的扬声器重现语音消息?
import com.google.cloud.texttospeech.v1.AudioEncoding;
import com.google.cloud.texttospeech.v1.SsmlVoiceGender;
import com.google.cloud.texttospeech.v1.SynthesisInput;
import com.google.cloud.texttospeech.v1.SynthesizeSpeechResponse;
import com.google.cloud.texttospeech.v1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1.VoiceSelectionParams;
import com.google.protobuf.ByteString;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class QuickstartSample {
public static void main(String... args) throws Exception {
// Instantiates a client
try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
// Set the text input to be synthesized
SynthesisInput input = SynthesisInput.newBuilder()
.setText("Hello, World!")
.build();
// Build the voice request, select the language code ("en-US") and the ssml voice gender
// ("neutral")
VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
.setLanguageCode("en-US")
.setSsmlGender(SsmlVoiceGender.NEUTRAL)
.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("output.mp3")) {
out.write(audioContents.toByteArray());
System.out.println("Audio content written to file \"output.mp3\"");
}
}
}
}
答案 0 :(得分:0)
您可以将音频内容转换为InputStream,然后使用javazoom Player播放
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice,audioConfig);
InputStream targetStream = new ByteArrayInputStream(response.getAudioContent().toByteArray());
Player playMP3;
playMP3 = new Player(targetStream);
playMP3.play();