SynthesizeSpeech - Amazon Polly
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

SynthesizeSpeech

以下 Java 代码示例演示如何使用基于 Java 的应用程序来合成包含较短文本的语音以进行近乎实时的处理。

有关更多信息,请参阅 SynthesizeSpeech API 参考。

package com.amazonaws.polly.samples; import com.amazonaws.services.polly.AmazonPolly; import com.amazonaws.services.polly.AmazonPollyClientBuilder; import com.amazonaws.services.polly.model.OutputFormat; import com.amazonaws.services.polly.model.SynthesizeSpeechRequest; import com.amazonaws.services.polly.model.SynthesizeSpeechResult; import com.amazonaws.services.polly.model.VoiceId; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; public class SynthesizeSpeechSample { AmazonPolly client = AmazonPollyClientBuilder.defaultClient(); public void synthesizeSpeech() { String outputFileName = "/tmp/speech.mp3"; SynthesizeSpeechRequest synthesizeSpeechRequest = new SynthesizeSpeechRequest() .withOutputFormat(OutputFormat.Mp3) .withVoiceId(VoiceId.Joanna) .withText("This is a sample text to be synthesized.") .withEngine("neural"); try (FileOutputStream outputStream = new FileOutputStream(new File(outputFileName))) { SynthesizeSpeechResult synthesizeSpeechResult = client.synthesizeSpeech(synthesizeSpeechRequest); byte[] buffer = new byte[2 * 1024]; int readBytes; try (InputStream in = synthesizeSpeechResult.getAudioStream()){ while ((readBytes = in.read(buffer)) > 0) { outputStream.write(buffer, 0, readBytes); } } } catch (Exception e) { System.err.println("Exception caught: " + e); } } }