Пример AWS Polly Java

Я пытаюсь выполнить простой пример Java службы AWS Polly,
Я использую код, предоставленный AWS в их документации,
Я создал простой проект Maven, используя следующее -
1. идентификатор группы - com.amazonaws.polly
2. идентификатор артефакта - java-демо
3. версия - 0.0.1-SNAPSHOT

Ниже приводится структура моего проекта -
введите описание изображения здесь

Следующее - мой pom.xml -

<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>

Следующий мой класс Java -

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) {

        //Didn't work
        //AWSCredentials credentials = new BasicAWSCredentials("someAccessKey","someSecretKey");
        //polly = new AmazonPollyClient(credentials);

        //Didn't work
        // 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);
        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();

    }
} 

Я выполняю код локально, поэтому в моей системе настроены учетные данные AWS IAM,
Мой пользователь IAM также имеет доступ к сервису AWS Polly.

Я получаю следующую ошибку при запуске кода -

Exception in thread "main" com.amazonaws.services.polly.model.AmazonPollyException: The security token included in the request is invalid. (Service: AmazonPolly; Status Code: 403; Error Code: UnrecognizedClientException; Request ID: 4d4b01fb-8015-11e8-8e18-4548f95fba92)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1586)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1254)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1035)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:747)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:721)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:704)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:672)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:654)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:518)
    at com.amazonaws.services.polly.AmazonPollyClient.doInvoke(AmazonPollyClient.java:668)
    at com.amazonaws.services.polly.AmazonPollyClient.invoke(AmazonPollyClient.java:644)
    at com.amazonaws.services.polly.AmazonPollyClient.describeVoices(AmazonPollyClient.java:383)
    at com.amazonaws.demos.polly.PollyDemo.<init>(PollyDemo.java:39)
    at com.amazonaws.demos.polly.PollyDemo.main(PollyDemo.java:54)

Я имею в виду следующий документ AWS для примера Java Полли - https://docs.aws.amazon.com/polly/latest/dg/examples-java.html

Может кто-нибудь помочь исправить мой код? Что я могу изменить в своем коде?

4 ответа

Это ошибка 403. Где вы передаете доступ к AWS и секретный ключ? Вы можете попробовать это

 * Constructs a new client to invoke service methods on AmazonPolly. A
 * credentials provider chain will be used that searches for credentials in
 * this order:
 * <ul>
 * <li>Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY</li>
 * <li>Java System Properties - aws.accessKeyId and aws.secretKey</li>
 * <li>Instance profile credentials delivered through the Amazon EC2
 * metadata service</li>
 * </ul>
 * <p>
 * All service calls made using this new client object are blocking, and
 * will not return until the service call completes.
 *
 * @see DefaultAWSCredentialsProviderChain
 */
public AmazonPollyClient() {
    this(new DefaultAWSCredentialsProviderChain(), new ClientConfiguration());
}

https://github.com/aws/aws-sdk-android/blob/master/aws-android-sdk-polly/src/main/java/com/amazonaws/services/polly/AmazonPollyClient.java

Replace

new DefaultAWSCredentialsProviderChain()

with

AWSStaticCredentialsProvider(new BasicAWSCredentials("AccessKey", "Secret Key"))

Я заметил, что в репозитории Github для этой службы нет файла POM. Мы это исправим. Вот файл POM, который работает.

<?xml version="1.0" encoding="UTF-8"?>
<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>pollyJ1Project</groupId>
<artifactId>pollyJ1Project</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
</properties>
<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.774</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.awaitility/awaitility -->
    <!-- https://mvnrepository.com/artifact/org.awaitility/awaitility -->
    <dependency>
        <groupId>org.awaitility</groupId>
        <artifactId>awaitility</artifactId>
        <version>4.0.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.awaitility</groupId>
        <artifactId>awaitility</artifactId>
        <version>4.0.2</version>
        <scope>compile</scope>
    </dependency>


</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Также - вот пример, который вы можете попробовать:

package com.amazonaws.polly.samples;

import com.amazonaws.services.polly.AmazonPolly;
import com.amazonaws.services.polly.AmazonPollyClientBuilder;
import com.amazonaws.services.polly.model.DescribeVoicesRequest;
import com.amazonaws.services.polly.model.DescribeVoicesResult;

 public class DescribeVoicesSample {

 public static void main(String[] args) {

    AmazonPolly client = AmazonPollyClientBuilder.defaultClient();

    describeVoices(client);

}
public static void describeVoices(AmazonPolly client ) {
    DescribeVoicesRequest allVoicesRequest = new DescribeVoicesRequest();
    DescribeVoicesRequest enUsVoicesRequest = new DescribeVoicesRequest()
            .withLanguageCode("en-US");

    try {
        String nextToken;
        do {
            DescribeVoicesResult allVoicesResult = 
        client.describeVoices(allVoicesRequest);
            nextToken = allVoicesResult.getNextToken();
            allVoicesRequest.setNextToken(nextToken);

            System.out.println("All voices: " + allVoicesResult.getVoices());
        } while (nextToken != null);

        do {
            DescribeVoicesResult enUsVoicesResult = client.describeVoices(enUsVoicesRequest);
            nextToken = enUsVoicesResult.getNextToken();
            enUsVoicesRequest.setNextToken(nextToken);

            System.out.println("en-US voices: " + enUsVoicesResult.getVoices());
        } while (nextToken != null);
    } catch (Exception e) {
        System.err.println("Exception caught: " + e);
    }
   }
  }

Приведенный выше код - V1. Вы можете найти примеры кода V2 здесь:

https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/example_code/polly

Я нашел здесь хорошую рабочую демонстрацию https://youtu.be/WMMSQAn_vHI . Это рабочий пример java для сервиса AWS Polly, использующий только новый DefaultAWSCredentialsProviderChain().

Другие вопросы по тегам