2

我正在尝试执行一个使用 AWS Polly 服务的简单 Java 示例。我正在使用 AWS 在其文档中提供的代码。我使用以下内容创建了一个简单的 Maven 项目 -**
1. group id - com.amazonaws.polly
2. artifact id - java-demo
3. version - 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)

我指的是 Polly java 示例的以下 AWS 文档 - https://docs.aws.amazon.com/polly/latest/dg/examples-java.html

有人可以帮助修复我的代码吗?我的代码有什么变化?

4

4 回答 4

2

这是一个 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

于 2018-07-05T06:38:38.547 回答
0

我注意到 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

于 2020-05-06T14:28:15.457 回答
0

代替

new DefaultAWSCredentialsProviderChain()

AWSStaticCredentialsProvider(new BasicAWSCredentials("AccessKey", "Secret Key"))
于 2020-06-23T13:21:34.683 回答
0

我在这里找到了一个不错的工作演示https://youtu.be/WMMSQAn_vHI。它是仅使用 new DefaultAWSCredentialsProviderChain() 的 AWS Polly 服务的工作 java 示例。

于 2021-03-28T05:58:41.980 回答