使用 SDK for Java 2.x 的 Amazon Transcribe 示例 - Amazon SDK for Java 2.x
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 SDK for Java 2.x 的 Amazon Transcribe 示例

以下代码示例向您展示了如何使用 Amazon SDK for Java 2.x 与 Amazon Transcribe 配合使用来执行操作和实现常见场景。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景 是展示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

操作

以下代码示例演示了如何使用 ListTranscriptionJobs

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

public class ListTranscriptionJobs { public static void main(String[] args) { TranscribeClient transcribeClient = TranscribeClient.builder() .region(Region.US_EAST_1) .build(); listTranscriptionJobs(transcribeClient); } public static void listTranscriptionJobs(TranscribeClient transcribeClient) { ListTranscriptionJobsRequest listJobsRequest = ListTranscriptionJobsRequest.builder() .build(); transcribeClient.listTranscriptionJobsPaginator(listJobsRequest).stream() .flatMap(response -> response.transcriptionJobSummaries().stream()) .forEach(jobSummary -> { System.out.println("Job Name: " + jobSummary.transcriptionJobName()); System.out.println("Job Status: " + jobSummary.transcriptionJobStatus()); System.out.println("Output Location: " + jobSummary.outputLocationType()); // Add more information as needed // Retrieve additional details for the job if necessary GetTranscriptionJobResponse jobDetails = transcribeClient.getTranscriptionJob( GetTranscriptionJobRequest.builder() .transcriptionJobName(jobSummary.transcriptionJobName()) .build()); // Display additional details System.out.println("Language Code: " + jobDetails.transcriptionJob().languageCode()); System.out.println("Media Format: " + jobDetails.transcriptionJob().mediaFormat()); // Add more details as needed System.out.println("--------------"); }); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考ListTranscriptionJobs中的。

以下代码示例演示了如何使用 StartTranscriptionJob

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

public class TranscribeStreamingDemoApp { private static final Region REGION = Region.US_EAST_1; private static TranscribeStreamingAsyncClient client; public static void main(String args[]) throws URISyntaxException, ExecutionException, InterruptedException, LineUnavailableException { client = TranscribeStreamingAsyncClient.builder() .credentialsProvider(getCredentials()) .region(REGION) .build(); CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000), new AudioStreamPublisher(getStreamFromMic()), getResponseHandler()); result.get(); client.close(); } private static InputStream getStreamFromMic() throws LineUnavailableException { // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono int sampleRate = 16000; AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); if (!AudioSystem.isLineSupported(info)) { System.out.println("Line not supported"); System.exit(0); } TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); line.open(format); line.start(); InputStream audioStream = new AudioInputStream(line); return audioStream; } private static AwsCredentialsProvider getCredentials() { return DefaultCredentialsProvider.create(); } private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) { return StartStreamTranscriptionRequest.builder() .languageCode(LanguageCode.EN_US.toString()) .mediaEncoding(MediaEncoding.PCM) .mediaSampleRateHertz(mediaSampleRateHertz) .build(); } private static StartStreamTranscriptionResponseHandler getResponseHandler() { return StartStreamTranscriptionResponseHandler.builder() .onResponse(r -> { System.out.println("Received Initial response"); }) .onError(e -> { System.out.println(e.getMessage()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); System.out.println("Error Occurred: " + sw.toString()); }) .onComplete(() -> { System.out.println("=== All records stream successfully ==="); }) .subscriber(event -> { List<Result> results = ((TranscriptEvent) event).transcript().results(); if (results.size() > 0) { if (!results.get(0).alternatives().get(0).transcript().isEmpty()) { System.out.println(results.get(0).alternatives().get(0).transcript()); } } }) .build(); } private InputStream getStreamFromFile(String audioFileName) { try { File inputFile = new File(getClass().getClassLoader().getResource(audioFileName).getFile()); InputStream audioStream = new FileInputStream(inputFile); return audioStream; } catch (FileNotFoundException e) { throw new RuntimeException(e); } } private static class AudioStreamPublisher implements Publisher<AudioStream> { private final InputStream inputStream; private static Subscription currentSubscription; private AudioStreamPublisher(InputStream inputStream) { this.inputStream = inputStream; } @Override public void subscribe(Subscriber<? super AudioStream> s) { if (this.currentSubscription == null) { this.currentSubscription = new SubscriptionImpl(s, inputStream); } else { this.currentSubscription.cancel(); this.currentSubscription = new SubscriptionImpl(s, inputStream); } s.onSubscribe(currentSubscription); } } public static class SubscriptionImpl implements Subscription { private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; private final Subscriber<? super AudioStream> subscriber; private final InputStream inputStream; private ExecutorService executor = Executors.newFixedThreadPool(1); private AtomicLong demand = new AtomicLong(0); SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) { this.subscriber = s; this.inputStream = inputStream; } @Override public void request(long n) { if (n <= 0) { subscriber.onError(new IllegalArgumentException("Demand must be positive")); } demand.getAndAdd(n); executor.submit(() -> { try { do { ByteBuffer audioBuffer = getNextEvent(); if (audioBuffer.remaining() > 0) { AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); subscriber.onNext(audioEvent); } else { subscriber.onComplete(); break; } } while (demand.decrementAndGet() > 0); } catch (Exception e) { subscriber.onError(e); } }); } @Override public void cancel() { executor.shutdown(); } private ByteBuffer getNextEvent() { ByteBuffer audioBuffer = null; byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; int len = 0; try { len = inputStream.read(audioBytes); if (len <= 0) { audioBuffer = ByteBuffer.allocate(0); } else { audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); } } catch (IOException e) { throw new UncheckedIOException(e); } return audioBuffer; } private AudioEvent audioEventFromBuffer(ByteBuffer bb) { return AudioEvent.builder() .audioChunk(SdkBytes.fromByteBuffer(bb)) .build(); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考StartTranscriptionJob中的。

场景

以下代码示例展示了如何:

  • 使用 Amazon Transcribe 开始转录作业。

  • 等待作业完成。

  • 获取存储转录的 URI。

有关更多信息,请参阅 Amazon Transcribe 入门

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

转录 PCM 文件。

/** * To run this AWS code example, ensure that you have set up your development * environment, including your AWS credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class TranscribeStreamingDemoFile { private static final Region REGION = Region.US_EAST_1; private static TranscribeStreamingAsyncClient client; public static void main(String args[]) throws ExecutionException, InterruptedException { final String USAGE = "\n" + "Usage:\n" + " <file> \n\n" + "Where:\n" + " file - the location of a PCM file to transcribe. In this example, ensure the PCM file is 16 hertz (Hz). \n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } String file = args[0]; client = TranscribeStreamingAsyncClient.builder() .region(REGION) .build(); CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000), new AudioStreamPublisher(getStreamFromFile(file)), getResponseHandler()); result.get(); client.close(); } private static InputStream getStreamFromFile(String file) { try { File inputFile = new File(file); InputStream audioStream = new FileInputStream(inputFile); return audioStream; } catch (FileNotFoundException e) { throw new RuntimeException(e); } } private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) { return StartStreamTranscriptionRequest.builder() .languageCode(LanguageCode.EN_US) .mediaEncoding(MediaEncoding.PCM) .mediaSampleRateHertz(mediaSampleRateHertz) .build(); } private static StartStreamTranscriptionResponseHandler getResponseHandler() { return StartStreamTranscriptionResponseHandler.builder() .onResponse(r -> { System.out.println("Received Initial response"); }) .onError(e -> { System.out.println(e.getMessage()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); System.out.println("Error Occurred: " + sw.toString()); }) .onComplete(() -> { System.out.println("=== All records stream successfully ==="); }) .subscriber(event -> { List<Result> results = ((TranscriptEvent) event).transcript().results(); if (results.size() > 0) { if (!results.get(0).alternatives().get(0).transcript().isEmpty()) { System.out.println(results.get(0).alternatives().get(0).transcript()); } } }) .build(); } private static class AudioStreamPublisher implements Publisher<AudioStream> { private final InputStream inputStream; private static Subscription currentSubscription; private AudioStreamPublisher(InputStream inputStream) { this.inputStream = inputStream; } @Override public void subscribe(Subscriber<? super AudioStream> s) { if (this.currentSubscription == null) { this.currentSubscription = new SubscriptionImpl(s, inputStream); } else { this.currentSubscription.cancel(); this.currentSubscription = new SubscriptionImpl(s, inputStream); } s.onSubscribe(currentSubscription); } } public static class SubscriptionImpl implements Subscription { private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; private final Subscriber<? super AudioStream> subscriber; private final InputStream inputStream; private ExecutorService executor = Executors.newFixedThreadPool(1); private AtomicLong demand = new AtomicLong(0); SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) { this.subscriber = s; this.inputStream = inputStream; } @Override public void request(long n) { if (n <= 0) { subscriber.onError(new IllegalArgumentException("Demand must be positive")); } demand.getAndAdd(n); executor.submit(() -> { try { do { ByteBuffer audioBuffer = getNextEvent(); if (audioBuffer.remaining() > 0) { AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); subscriber.onNext(audioEvent); } else { subscriber.onComplete(); break; } } while (demand.decrementAndGet() > 0); } catch (Exception e) { subscriber.onError(e); } }); } @Override public void cancel() { executor.shutdown(); } private ByteBuffer getNextEvent() { ByteBuffer audioBuffer = null; byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; int len = 0; try { len = inputStream.read(audioBytes); if (len <= 0) { audioBuffer = ByteBuffer.allocate(0); } else { audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); } } catch (IOException e) { throw new UncheckedIOException(e); } return audioBuffer; } private AudioEvent audioEventFromBuffer(ByteBuffer bb) { return AudioEvent.builder() .audioChunk(SdkBytes.fromByteBuffer(bb)) .build(); } } }

转录来自计算机麦克风的流音频。

public class TranscribeStreamingDemoApp { private static final Region REGION = Region.US_EAST_1; private static TranscribeStreamingAsyncClient client; public static void main(String args[]) throws URISyntaxException, ExecutionException, InterruptedException, LineUnavailableException { client = TranscribeStreamingAsyncClient.builder() .credentialsProvider(getCredentials()) .region(REGION) .build(); CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000), new AudioStreamPublisher(getStreamFromMic()), getResponseHandler()); result.get(); client.close(); } private static InputStream getStreamFromMic() throws LineUnavailableException { // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono int sampleRate = 16000; AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false); DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); if (!AudioSystem.isLineSupported(info)) { System.out.println("Line not supported"); System.exit(0); } TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); line.open(format); line.start(); InputStream audioStream = new AudioInputStream(line); return audioStream; } private static AwsCredentialsProvider getCredentials() { return DefaultCredentialsProvider.create(); } private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) { return StartStreamTranscriptionRequest.builder() .languageCode(LanguageCode.EN_US.toString()) .mediaEncoding(MediaEncoding.PCM) .mediaSampleRateHertz(mediaSampleRateHertz) .build(); } private static StartStreamTranscriptionResponseHandler getResponseHandler() { return StartStreamTranscriptionResponseHandler.builder() .onResponse(r -> { System.out.println("Received Initial response"); }) .onError(e -> { System.out.println(e.getMessage()); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); System.out.println("Error Occurred: " + sw.toString()); }) .onComplete(() -> { System.out.println("=== All records stream successfully ==="); }) .subscriber(event -> { List<Result> results = ((TranscriptEvent) event).transcript().results(); if (results.size() > 0) { if (!results.get(0).alternatives().get(0).transcript().isEmpty()) { System.out.println(results.get(0).alternatives().get(0).transcript()); } } }) .build(); } private InputStream getStreamFromFile(String audioFileName) { try { File inputFile = new File(getClass().getClassLoader().getResource(audioFileName).getFile()); InputStream audioStream = new FileInputStream(inputFile); return audioStream; } catch (FileNotFoundException e) { throw new RuntimeException(e); } } private static class AudioStreamPublisher implements Publisher<AudioStream> { private final InputStream inputStream; private static Subscription currentSubscription; private AudioStreamPublisher(InputStream inputStream) { this.inputStream = inputStream; } @Override public void subscribe(Subscriber<? super AudioStream> s) { if (this.currentSubscription == null) { this.currentSubscription = new SubscriptionImpl(s, inputStream); } else { this.currentSubscription.cancel(); this.currentSubscription = new SubscriptionImpl(s, inputStream); } s.onSubscribe(currentSubscription); } } public static class SubscriptionImpl implements Subscription { private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; private final Subscriber<? super AudioStream> subscriber; private final InputStream inputStream; private ExecutorService executor = Executors.newFixedThreadPool(1); private AtomicLong demand = new AtomicLong(0); SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) { this.subscriber = s; this.inputStream = inputStream; } @Override public void request(long n) { if (n <= 0) { subscriber.onError(new IllegalArgumentException("Demand must be positive")); } demand.getAndAdd(n); executor.submit(() -> { try { do { ByteBuffer audioBuffer = getNextEvent(); if (audioBuffer.remaining() > 0) { AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); subscriber.onNext(audioEvent); } else { subscriber.onComplete(); break; } } while (demand.decrementAndGet() > 0); } catch (Exception e) { subscriber.onError(e); } }); } @Override public void cancel() { executor.shutdown(); } private ByteBuffer getNextEvent() { ByteBuffer audioBuffer = null; byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; int len = 0; try { len = inputStream.read(audioBytes); if (len <= 0) { audioBuffer = ByteBuffer.allocate(0); } else { audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); } } catch (IOException e) { throw new UncheckedIOException(e); } return audioBuffer; } private AudioEvent audioEventFromBuffer(ByteBuffer bb) { return AudioEvent.builder() .audioChunk(SdkBytes.fromByteBuffer(bb)) .build(); } } }