Esempio di Java - Amazon Polly

Esempio di Java

Questo esempio mostra come utilizzare Amazon Polly per lo streaming vocale da un'applicazione basata su Java. Nell'esempio viene utilizzato AWS SDK for Java per leggere il testo specificato utilizzando una voce selezionata da un elenco.

Il codice mostrato copre le attività principali, ma esegue solo un controllo minimo degli errori. Se Amazon Polly rileva un errore, l'applicazione viene terminata.

Per eseguire questa applicazione di esempio, è necessario quanto elencato di seguito:

Per testare l'applicazione

  1. Verifica che la variabile di ambiente JAVA_HOME sia impostata per il JDK.

    Ad esempio, se hai installato JDK 1.8.0_121 su Windows nel percorso C:\Program Files\Java\jdk1.8.0_121, digita quanto segue al prompt dei comandi:

    set JAVA_HOME=""C:\Program Files\Java\jdk1.8.0_121""

    Se hai installato JDK 1.8.0_121 su Linux nel percorso /usr/lib/jvm/java8-openjdk-amd64, digita quanto segue al prompt dei comandi:

    export JAVA_HOME=/usr/lib/jvm/java8-openjdk-amd64
  2. Imposta le variabili di ambiente Maven per eseguire Maven dalla riga di comando.

    Ad esempio, se hai installato Maven 3.3.9 su Windows nel percorso C:\Program Files\apache-maven-3.3.9, digita quanto segue al prompt dei comandi:

    set M2_HOME=""C:\Program Files\apache-maven-3.3.9"" set M2=%M2_HOME%\bin set PATH=%M2%;%PATH%

    Se hai installato Maven 3.3.9 su Linux nel percorso /home/ec2-user/opt/apache-maven-3.3.9, digita quanto segue al prompt dei comandi:

    export M2_HOME=/home/ec2-user/opt/apache-maven-3.3.9 export M2=$M2_HOME/bin export PATH=$M2:$PATH
  3. Crea una nuova directory denominata polly-java-demo.

  4. Nella directory polly-java-demo crea un nuovo file denominato pom.xml e incollavi il seguente codice:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.amazonaws.polly</groupId> <artifactId>java-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-polly --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-polly</artifactId> <version>1.11.77</version> </dependency> <!-- https://mvnrepository.com/artifact/com.googlecode.soundlibs/jlayer --> <dependency> <groupId>com.googlecode.soundlibs</groupId> <artifactId>jlayer</artifactId> <version>1.0.1-1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <goals> <goal>java</goal> </goals> </execution> </executions> <configuration> <mainClass>com.amazonaws.demos.polly.PollyDemo</mainClass> </configuration> </plugin> </plugins> </build> </project>
  5. Crea una nuova directory denominata polly nel percorso src/main/java/com/amazonaws/demos.

  6. Nella directory polly crea un nuovo file di origine Java denominato PollyDemo.java e incolla il seguente codice:

    package com.amazonaws.demos.polly; import java.io.IOException; import java.io.InputStream; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.polly.AmazonPollyClient; import com.amazonaws.services.polly.model.DescribeVoicesRequest; import com.amazonaws.services.polly.model.DescribeVoicesResult; 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.Voice; import javazoom.jl.player.advanced.AdvancedPlayer; import javazoom.jl.player.advanced.PlaybackEvent; import javazoom.jl.player.advanced.PlaybackListener; public class PollyDemo { private final AmazonPollyClient polly; private final Voice voice; private static final String SAMPLE = "Congratulations. You have successfully built this working demo of Amazon Polly in Java. Have fun building voice enabled apps with Amazon Polly (that's me!), and always look at the AWS website for tips and tricks on using Amazon Polly and other great services from AWS"; public PollyDemo(Region region) { // create an Amazon Polly client in a specific region polly = new AmazonPollyClient(new DefaultAWSCredentialsProviderChain(), new ClientConfiguration()); polly.setRegion(region); // Create describe voices request. DescribeVoicesRequest describeVoicesRequest = new DescribeVoicesRequest(); // Synchronously ask Amazon Polly to describe available TTS voices. DescribeVoicesResult describeVoicesResult = polly.describeVoices(describeVoicesRequest); voice = describeVoicesResult.getVoices().get(0); } public InputStream synthesize(String text, OutputFormat format) throws IOException { SynthesizeSpeechRequest synthReq = new SynthesizeSpeechRequest().withText(text).withVoiceId(voice.getId()) .withOutputFormat(format).withEngine("neural"); SynthesizeSpeechResult synthRes = polly.synthesizeSpeech(synthReq); return synthRes.getAudioStream(); } public static void main(String args[]) throws Exception { //create the test class PollyDemo helloWorld = new PollyDemo(Region.getRegion(Regions.US_EAST_1)); //get the audio stream InputStream speechStream = helloWorld.synthesize(SAMPLE, OutputFormat.Mp3); //create an MP3 player AdvancedPlayer player = new AdvancedPlayer(speechStream, javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice()); player.setPlayBackListener(new PlaybackListener() { @Override public void playbackStarted(PlaybackEvent evt) { System.out.println("Playback started"); System.out.println(SAMPLE); } @Override public void playbackFinished(PlaybackEvent evt) { System.out.println("Playback finished"); } }); // play it! player.play(); } }
  7. Torna alla directory polly-java-demo per pulire, compilare ed eseguire la demo:

    mvn clean compile exec:java