本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
搭StartTranscriptionJob
配 AWS 開發套件或 CLI 使用
下列程式碼範例會示範如何使用StartTranscriptionJob
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- .NET
-
- AWS SDK for .NET
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 /// <summary> /// Start a transcription job for a media file. This method returns /// as soon as the job is started. /// </summary> /// <param name="jobName">A unique name for the transcription job.</param> /// <param name="mediaFileUri">The URI of the media file, typically an Amazon S3 location.</param> /// <param name="mediaFormat">The format of the media file.</param> /// <param name="languageCode">The language code of the media file, such as en-US.</param> /// <param name="vocabularyName">Optional name of a custom vocabulary.</param> /// <returns>A TranscriptionJob instance with information on the new job.</returns> public async Task<TranscriptionJob> StartTranscriptionJob(string jobName, string mediaFileUri, MediaFormat mediaFormat, LanguageCode languageCode, string? vocabularyName) { var response = await _amazonTranscribeService.StartTranscriptionJobAsync( new StartTranscriptionJobRequest() { TranscriptionJobName = jobName, Media = new Media() { MediaFileUri = mediaFileUri }, MediaFormat = mediaFormat, LanguageCode = languageCode, Settings = vocabularyName != null ? new Settings() { VocabularyName = vocabularyName } : null }); return response.TranscriptionJob; }
-
如需 API 詳細資訊,請參閱 AWS SDK for .NET API 參考StartTranscriptionJob中的。
-
- CLI
-
- AWS CLI
-
範例 1:轉錄音訊檔案
以下
start-transcription-job
範例會轉錄您的音訊檔案。aws transcribe start-transcription-job \ --cli-input-json
file://myfile.json
myfile.json
的內容:{ "TranscriptionJobName": "cli-simple-transcription-job", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" } }
如需詳細資訊,請參閱 Amazon Transcribe 開發人員指南中的入門 (AWS 命令列界面)。
範例 2:轉錄多聲道音訊檔案
以下
start-transcription-job
範例會轉錄您的多聲道音訊檔案。aws transcribe start-transcription-job \ --cli-input-json
file://mysecondfile.json
mysecondfile.json
的內容:{ "TranscriptionJobName": "cli-channelid-job", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "Settings":{ "ChannelIdentification":true } }
輸出:
{ "TranscriptionJob": { "TranscriptionJobName": "cli-channelid-job", "TranscriptionJobStatus": "IN_PROGRESS", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "StartTime": "2020-09-17T16:07:56.817000+00:00", "CreationTime": "2020-09-17T16:07:56.784000+00:00", "Settings": { "ChannelIdentification": true } } }
如需詳細資訊,請參閱《Amazon Transcribe 開發人員指南》中的轉錄多聲道音訊。
範例 3:轉錄音訊檔案並識別不同的發言者
以下
start-transcription-job
範例會轉錄音訊檔案,並識別轉錄輸出中的發言者。aws transcribe start-transcription-job \ --cli-input-json
file://mythirdfile.json
mythirdfile.json
的內容:{ "TranscriptionJobName": "cli-speakerid-job", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "Settings":{ "ShowSpeakerLabels": true, "MaxSpeakerLabels": 2 } }
輸出:
{ "TranscriptionJob": { "TranscriptionJobName": "cli-speakerid-job", "TranscriptionJobStatus": "IN_PROGRESS", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "StartTime": "2020-09-17T16:22:59.696000+00:00", "CreationTime": "2020-09-17T16:22:59.676000+00:00", "Settings": { "ShowSpeakerLabels": true, "MaxSpeakerLabels": 2 } } }
如需詳細資訊,請參閱《Amazon Transcribe 開發人員指南》中的識別發言者。
範例 4:轉錄音訊檔案,並在轉錄輸出中為任何不希望出現的字詞加上遮罩
以下
start-transcription-job
範例會轉錄音訊檔案,並使用您先前建立的詞彙篩選器來為任何不希望出現的字詞加上遮罩。aws transcribe start-transcription-job \ --cli-input-json
file://myfourthfile.json
myfourthfile.json
的內容:{ "TranscriptionJobName": "cli-filter-mask-job", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "Settings":{ "VocabularyFilterName": "your-vocabulary-filter", "VocabularyFilterMethod": "mask" } }
輸出:
{ "TranscriptionJob": { "TranscriptionJobName": "cli-filter-mask-job", "TranscriptionJobStatus": "IN_PROGRESS", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension" }, "StartTime": "2020-09-18T16:36:18.568000+00:00", "CreationTime": "2020-09-18T16:36:18.547000+00:00", "Settings": { "VocabularyFilterName": "your-vocabulary-filter", "VocabularyFilterMethod": "mask" } } }
如需詳細資訊,請參閱《Amazon Transcribe 開發人員指南》中的篩選轉錄。
範例 5:轉錄音訊檔案,並移除轉錄輸出中任何不希望出現的字詞
以下
start-transcription-job
範例會轉錄音訊檔案,並使用您先前建立的詞彙篩選器來為任何不希望出現的字詞加上遮罩。aws transcribe start-transcription-job \ --cli-input-json
file://myfifthfile.json
myfifthfile.json
的內容:{ "TranscriptionJobName": "cli-filter-remove-job", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "Settings":{ "VocabularyFilterName": "your-vocabulary-filter", "VocabularyFilterMethod": "remove" } }
輸出:
{ "TranscriptionJob": { "TranscriptionJobName": "cli-filter-remove-job", "TranscriptionJobStatus": "IN_PROGRESS", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "StartTime": "2020-09-18T16:36:18.568000+00:00", "CreationTime": "2020-09-18T16:36:18.547000+00:00", "Settings": { "VocabularyFilterName": "your-vocabulary-filter", "VocabularyFilterMethod": "remove" } } }
如需詳細資訊,請參閱《Amazon Transcribe 開發人員指南》中的篩選轉錄。
範例 6:使用自訂詞彙以更準確的方式轉錄音訊檔案
以下
start-transcription-job
範例會轉錄音訊檔案,並使用您先前建立的詞彙篩選器來為任何不希望出現的字詞加上遮罩。aws transcribe start-transcription-job \ --cli-input-json
file://mysixthfile.json
mysixthfile.json
的內容:{ "TranscriptionJobName": "cli-vocab-job", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "Settings":{ "VocabularyName": "your-vocabulary" } }
輸出:
{ "TranscriptionJob": { "TranscriptionJobName": "cli-vocab-job", "TranscriptionJobStatus": "IN_PROGRESS", "LanguageCode": "the-language-of-your-transcription-job", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "StartTime": "2020-09-18T16:36:18.568000+00:00", "CreationTime": "2020-09-18T16:36:18.547000+00:00", "Settings": { "VocabularyName": "your-vocabulary" } } }
如需詳細資訊,請參閱《Amazon Transcribe 開發人員指南》中的篩選轉錄。
範例 7:識別音訊檔案的語言並進行轉錄
以下
start-transcription-job
範例會轉錄音訊檔案,並使用您先前建立的詞彙篩選器來為任何不希望出現的字詞加上遮罩。aws transcribe start-transcription-job \ --cli-input-json
file://myseventhfile.json
myseventhfile.json
的內容:{ "TranscriptionJobName": "cli-identify-language-transcription-job", "IdentifyLanguage": true, "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" } }
輸出:
{ "TranscriptionJob": { "TranscriptionJobName": "cli-identify-language-transcription-job", "TranscriptionJobStatus": "IN_PROGRESS", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/Amazon-S3-prefix/your-media-file-name.file-extension" }, "StartTime": "2020-09-18T22:27:23.970000+00:00", "CreationTime": "2020-09-18T22:27:23.948000+00:00", "IdentifyLanguage": true } }
如需詳細資訊,請參閱《Amazon Transcribe 開發人員指南》中的識別語言。
範例 8:轉錄包含已修訂的個人身分識別資訊的音訊檔案
以下
start-transcription-job
範例會轉錄音訊檔案,並修訂轉錄輸出中的任何個人身分識別資訊。aws transcribe start-transcription-job \ --cli-input-json
file://myeighthfile.json
myeigthfile.json
的內容:{ "TranscriptionJobName": "cli-redaction-job", "LanguageCode": "language-code", "Media": { "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension" }, "ContentRedaction": { "RedactionOutput":"redacted", "RedactionType":"PII" } }
輸出:
{ "TranscriptionJob": { "TranscriptionJobName": "cli-redaction-job", "TranscriptionJobStatus": "IN_PROGRESS", "LanguageCode": "language-code", "Media": { "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension" }, "StartTime": "2020-09-25T23:49:13.195000+00:00", "CreationTime": "2020-09-25T23:49:13.176000+00:00", "ContentRedaction": { "RedactionType": "PII", "RedactionOutput": "redacted" } } }
如需詳細資訊,請參閱《Amazon Transcribe 開發人員指南》中的自動內容修訂。
範例 9:產生包含已修訂個人身分識別資訊 (PII) 的文字記錄和未修訂的文字記錄
以下
start-transcription-job
範例會產生音訊檔案的兩個轉錄,一個包含已修訂的個人身分識別資訊,另一個則不包含任何修訂。aws transcribe start-transcription-job \ --cli-input-json
file://myninthfile.json
myninthfile.json
的內容:{ "TranscriptionJobName": "cli-redaction-job-with-unredacted-transcript", "LanguageCode": "language-code", "Media": { "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension" }, "ContentRedaction": { "RedactionOutput":"redacted_and_unredacted", "RedactionType":"PII" } }
輸出:
{ "TranscriptionJob": { "TranscriptionJobName": "cli-redaction-job-with-unredacted-transcript", "TranscriptionJobStatus": "IN_PROGRESS", "LanguageCode": "language-code", "Media": { "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension" }, "StartTime": "2020-09-25T23:59:47.677000+00:00", "CreationTime": "2020-09-25T23:59:47.653000+00:00", "ContentRedaction": { "RedactionType": "PII", "RedactionOutput": "redacted_and_unredacted" } } }
如需詳細資訊,請參閱《Amazon Transcribe 開發人員指南》中的自動內容修訂。
範例 10:使用您先前建立的自訂語言模型來轉錄音訊檔案。
以下
start-transcription-job
範例會使用您先前建立的自訂語言模型來轉錄音訊檔案。aws transcribe start-transcription-job \ --cli-input-json
file://mytenthfile.json
mytenthfile.json
的內容:{ "TranscriptionJobName": "cli-clm-2-job-1", "LanguageCode": "language-code", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/your-audio-file.file-extension" }, "ModelSettings": { "LanguageModelName":"cli-clm-2" } }
輸出:
{ "TranscriptionJob": { "TranscriptionJobName": "cli-clm-2-job-1", "TranscriptionJobStatus": "IN_PROGRESS", "LanguageCode": "language-code", "Media": { "MediaFileUri": "s3://DOC-EXAMPLE-BUCKET/your-audio-file.file-extension" }, "StartTime": "2020-09-28T17:56:01.835000+00:00", "CreationTime": "2020-09-28T17:56:01.801000+00:00", "ModelSettings": { "LanguageModelName": "cli-clm-2" } } }
如需詳細資訊,請參閱《Amazon Transcribe 開發人員指南》中的使用自訂語言模型改善特定領域的轉錄準確性。
-
如需 API 詳細資訊,請參閱AWS CLI 命令參考StartTranscriptionJob
中的。
-
- Java
-
- 適用於 Java 2.x 的 SDK
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 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 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考StartTranscriptionJob中的。
-
- JavaScript
-
- 適用於 JavaScript (v3) 的開發套件
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 開始轉錄作業。
// Import the required AWS SDK clients and commands for Node.js import { StartTranscriptionJobCommand } from "@aws-sdk/client-transcribe"; import { transcribeClient } from "./libs/transcribeClient.js"; // Set the parameters export const params = { TranscriptionJobName: "JOB_NAME", LanguageCode: "LANGUAGE_CODE", // For example, 'en-US' MediaFormat: "SOURCE_FILE_FORMAT", // For example, 'wav' Media: { MediaFileUri: "SOURCE_LOCATION", // For example, "https://transcribe-demo.s3-REGION.amazonaws.com/hello_world.wav" }, OutputBucketName: "OUTPUT_BUCKET_NAME" }; export const run = async () => { try { const data = await transcribeClient.send( new StartTranscriptionJobCommand(params) ); console.log("Success - put", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run();
建立用戶端。
import { TranscribeClient } from "@aws-sdk/client-transcribe"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon Transcribe service client object. const transcribeClient = new TranscribeClient({ region: REGION }); export { transcribeClient };
-
如需詳細資訊,請參閱《AWS SDK for JavaScript 開發人員指南》。
-
如需 API 詳細資訊,請參閱 AWS SDK for JavaScript API 參考StartTranscriptionJob中的。
-
- Python
-
- 適用於 Python (Boto3) 的 SDK
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 def start_job( job_name, media_uri, media_format, language_code, transcribe_client, vocabulary_name=None, ): """ Starts a transcription job. This function returns as soon as the job is started. To get the current status of the job, call get_transcription_job. The job is successfully completed when the job status is 'COMPLETED'. :param job_name: The name of the transcription job. This must be unique for your AWS account. :param media_uri: The URI where the audio file is stored. This is typically in an Amazon S3 bucket. :param media_format: The format of the audio file. For example, mp3 or wav. :param language_code: The language code of the audio file. For example, en-US or ja-JP :param transcribe_client: The Boto3 Transcribe client. :param vocabulary_name: The name of a custom vocabulary to use when transcribing the audio file. :return: Data about the job. """ try: job_args = { "TranscriptionJobName": job_name, "Media": {"MediaFileUri": media_uri}, "MediaFormat": media_format, "LanguageCode": language_code, } if vocabulary_name is not None: job_args["Settings"] = {"VocabularyName": vocabulary_name} response = transcribe_client.start_transcription_job(**job_args) job = response["TranscriptionJob"] logger.info("Started transcription job %s.", job_name) except ClientError: logger.exception("Couldn't start transcription job %s.", job_name) raise else: return job
-
如需 API 的詳細資訊,請參閱AWS 開發套件StartTranscriptionJob中的 Python (博托 3) API 參考。
-
如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱搭配 AWS SDK 使用此服務。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。