java - AWS Polly Java 示例

标签 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)

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

有人可以帮助修复我的代码吗?我需要更改代码中的哪些内容?

最佳答案

这是一个 403 错误。您将 AWS 访问权限和 key 传递到哪里?你可以试试这个

 * 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

关于java - AWS Polly Java 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51184130/

相关文章:

java - Spring mongodb 统计集合中的所有文档

从 r 中的 s3 中一个一个地读取文件

amazon-web-services - 使用 POST 请求在 AWS S3 上基于浏览器上传文件

mysql - 如何在 AWS RDS 中将时区设置为 EST

aws-sdk - 有没有办法使用 sdk 更新 api 键值?

node.js - 使用aws cognito权限规则自定义node.js api的授权

java - 通过jSoup从Div标签获取属性值

java - (Java)包组织有最佳实践吗?

java - 在我的应用程序中硬编码我的 keystore 的密码可以吗?

amazon-web-services - 如何生成涉及多个指标的AWS CloudWatch警报