AWS Polly Java示例

时间:2018-07-05 05:47:20

标签: java amazon-web-services aws-sdk aws-java-sdk amazon-polly

我正在尝试执行一个简单的AWS Polly服务的Java示例,
我正在使用AWS在其文档中提供的代码,
我使用以下内容创建了一个简单的Maven项目-
1。组ID- com.amazonaws.polly
2。工件ID- java-demo
3。版本- 0.0.1-SNAPSHOT

以下是我的项目结构-
enter image description here

以下是我的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 Doc作为Polly Java示例- https://docs.aws.amazon.com/polly/latest/dg/examples-java.html

有人可以修复我的代码吗?我要更改我的代码吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我注意到Github存储库中没有用于该服务的POM文件。我们将解决此问题。这是一个有效的POM文件。

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);
    }
   }
  }

也-这是您可以尝试的示例:

git init 

git commit -m "first commit"

git remote add origin [url-for-github-repo]

git push -u origin master

上面的代码是V1。您可以在此处找到V2代码示例:

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

答案 2 :(得分:0)

替换

new DefaultAWSCredentialsProviderChain()

使用

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

答案 3 :(得分:0)

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