准备浏览器脚本 - AWS SDK for JavaScript

帮助我们改进AWS SDK for JavaScript版本 3 (V3) 文档,方法是使用反馈链接,或者在上创建议题或拉取请求GitHub.

这些区域有:AWS SDK for JavaScriptV3 API 参考指南详细描述了所有的 API 操作AWS SDK for JavaScript版本 3 (V3)。

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

准备浏览器脚本

本主题是关于构建应用程序的教程的一部分,该应用程序可以为经过身份验证的用户转录和显示语音 要开始使用本教程,请参阅用经过身份验证的用户构建转录应用

有三个文件,index.htmlrecorder.js, 和helper.js,你需要将它们捆绑成一个main.js使用 Webpack。本主题仅详细介绍了中的函数index.js使用 SDKJavaScript,这是可用的此处GitHub.

注意

recorder.jshelper.js是必需的,但是由于它们不包含 Node.js 代码,因此在内联评论中进行了解释这里这里分别地GitHub.

首先,定义参数。COGNITO_ID是 Amazon Cognito 在创建AWS资源 本教程的主题。格式为cognito-idp.AWS_REGION.amazonaws.com/USER_POOL_ID. 用户池 ID 为ID_TOKEN中的AWS凭证令牌,该令牌被从应用程序 URL 中剥离getToken函数在 'helper.js' 文件中。这个令牌被传递给loginData变量,它为 Amazon Transcribe 和 Amazon S3 客户端对象提供登录名。Replace“地区”使用AWS地区,以及“存储桶”用替换“身份 _POOL_ID”使用IdentityPoolId来自 的示例页面为此示例创建的 Amazon Cognito 身份池。这也会传递给每个客户端对象。

// Import the required AWS SDK clients and commands for Node.js import "./helper.js"; import "./recorder.js"; import { CognitoIdentityClient } from"@aws-sdk/client-cognito-identity"; import { fromCognitoIdentityPool, } from"@aws-sdk/credential-provider-cognito-identity"; import { CognitoIdentityProviderClient, GetUserCommand, } from"@aws-sdk/client-cognito-identity-provider"; import { S3RequestPresigner } from"@aws-sdk/s3-request-presigner"; import { createRequest } from"@aws-sdk/util-create-request"; import { formatUrl } from"@aws-sdk/util-format-url"; import { TranscribeClient, StartTranscriptionJobCommand, } from"@aws-sdk/client-transcribe"; import { S3Client, PutObjectCommand, GetObjectCommand, ListObjectsCommand, DeleteObjectCommand, } from"@aws-sdk/client-s3"; import fetch from "node-fetch"; // Set the parameters. // 'COGINTO_ID' has the format 'cognito-idp.eu-west-1.amazonaws.com/COGNITO_ID'. let COGNITO_ID = "COGNITO_ID"; // Get the Amazon Cognito ID token for the user. 'getToken()' is in 'helper.js'. let idToken = getToken(); let loginData = { [COGNITO_ID]: idToken, }; const params = { Bucket: "BUCKET", // The Amazon Simple Storage Solution (S3) bucket to store the transcriptions. Region: "REGION", // The AWS Region identityPoolID: "IDENTITY_POOL_ID", // Amazon Cognito Identity Pool ID. }; // Create an Amazon Transcribe service client object. const client = new TranscribeClient({ region: params.Region, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: params.Region }), identityPoolId: params.identityPoolID, logins: loginData, }), }); // Create an Amazon S3 client object. const s3Client = new S3Client({ region: params.Region, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: params.Region }), identityPoolId: params.identityPoolID, logins: loginData, }), });

当 HTML 页面加载时,updateUserInterface如果用户首次登录应用程序,则在 Amazon S3 存储桶中创建一个带有用户名的文件夹。否则,它会使用用户之前会话中的任何成绩单更新用户界面。

let updateUserInterface; window.onload = updateUserInterface = async () => { // Set the parameters. const userParams = { // Get the access token. 'GetAccessToken()' is in 'helper.js'. AccessToken: getAccessToken(), }; // Create a CognitoIdentityProviderClient client object. const client = new CognitoIdentityProviderClient({ region: params.Region }); try { const data = await client.send(new GetUserCommand(userParams)); const username = data.Username; // Export username for use in 'recorder.js'. exports.username = username; try { // If this is user's first sign-in, create a folder with user's name in Amazon S3 bucket. // Otherwise, no effect. const Key = `${username}/`; try { const data = await s3Client.send( new PutObjectCommand({ Key: Key, Bucket: params.Bucket }) ); console.log("Folder created for user ", data.Username); } catch (err) { console.log("Error", err); } try { // Get a list of the objects in the Amazon S3 bucket. const data = await s3Client.send( new ListObjectsCommand({ Bucket: params.Bucket, Prefix: username }) ); // Create a variable for the list of objects in the Amazon S3 bucket. const output = data.Contents; // Loop through the objects, populating a row on the user interface for each object. for (var i = 0; i < output.length; i++) { var obj = output[i]; const objectParams = { Bucket: params.Bucket, Key: obj.Key, }; // Get the name of the object from the Amazon S3 bucket. const data = await s3Client.send(new GetObjectCommand(objectParams)); // Extract the body contents, a readable stream, from the returned data. const result = data.Body; // Create a variable for the string version of the readable stream. let stringResult = ""; // Use 'yeidlUnit8Chunks' to convert the readable streams into JSON. for await (let chunk of yieldUint8Chunks(result)) { stringResult += String.fromCharCode.apply(null, chunk); } // The setTimeout function waits while readable stream is converted into JSON. setTimeout(function () { // Parse JSON into human readable transcript, which will be displayed on user interface (UI). const outputJSON = JSON.parse(stringResult).results.transcripts[0] .transcript; // Create name for transcript, which will be displayed. const outputJSONTime = JSON.parse(stringResult) .jobName.split("/")[0] .replace("-job", ""); i++; // // Display the details for the transcription on the UI. // 'displayTranscriptionDetails()' is in 'helper.js'. displayTranscriptionDetails( i, outputJSONTime, objectParams.Key, outputJSON ); }, 1000); } } catch (err) { console.log("Error", err); } } catch (err) { console.log("Error creating presigned URL", err); } } catch (err) { console.log("Error", err); } }; // Convert readable streams. async function* yieldUint8Chunks(data) { const reader = data.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) return; yield value; } } finally { reader.releaseLock(); } }

当用户记录语音留言以进行转录时,upload将录音上传到 Amazon S3 存储桶。调用此函数从recorder.js文件。

// Upload recordings to Amazon S3 bucket window.upload = async function (blob, userName) { // Set the parameters for the recording recording. const Key = `${userName}/test-object-${Math.ceil(Math.random() * 10 ** 10)}`; // Create a presigned URL to upload the transcription to the Amazon S3 bucket when it is ready. try { // Create an Amazon S3RequestPresigner object. const signer = new S3RequestPresigner({ ...s3Client.config }); // Create the request. const request = await createRequest( s3Client, new PutObjectCommand({ Key, Bucket: params.Bucket }) ); // Define the duration until expiration of the presigned URL. const expiration = new Date(Date.now() + 60 * 60 * 1000); // Create and format the presigned URL. let signedUrl; signedUrl = formatUrl(await signer.presign(request, expiration)); console.log(`\nPutting "${Key}"`); } catch (err) { console.log("Error creating presigned URL", err); } try { // Upload the object to the Amazon S3 bucket using a presigned URL. response = await fetch(signedUrl, { method: "PUT", headers: { "content-type": "application/octet-stream", }, body: blob, }); // Create the transcription job name. In this case, it's the current date and time. const today = new Date(); const date = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate(); const time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds(); const jobName = date + "-time-" + time; // Call the "createTranscriptionJob()" function. createTranscriptionJob( "s3://" + params.Bucket + "/" + Key, jobName, params.Bucket, Key ); } catch (err) { console.log("Error uploading object", err); } }; // Create the AWS Transcribe transcription job. const createTranscriptionJob = async (recording, jobName, bucket, key) => { // Set the parameters for transcriptions job const params = { TranscriptionJobName: jobName + "-job", LanguageCode: "en-US", // For example, 'en-US', OutputBucketName: bucket, OutputKey: key, Media: { MediaFileUri: recording, // For example, "https://transcribe-demo.s3-REGION.amazonaws.com/hello_world.wav" }, }; try { // Start the transcription job. const data = await client.send(new StartTranscriptionJobCommand(params)); console.log("Success - transcription submitted", data); } catch (err) { console.log("Error", err); } };

deleteTranscription从用户界面中删除转录,然后deleteRow从 Amazon S3 存储桶中删除现有转录。两者都是由Delete按钮在用户界面上。

// Delete a transcription from the Amazon S3 bucket. window.deleteJSON = async (jsonFileName) => { try { const data = await s3Client.send( new DeleteObjectCommand({ Bucket: params.Bucket, Key: jsonFileName, }) ); console.log("Success - JSON deleted"); } catch (err) { console.log("Error", err); } }; // Delete a row from the user interface. window.deleteRow = function (rowid) { const row = document.getElementById(rowid); row.parentNode.removeChild(row); };

最后,在命令提示符处运行以下命令,将JavaScript对于此示例,在名为的文件中main.js

webpack index.js --mode development --target web --devtool false -o main.js
注意

有关安装的信息,请参阅使用 webpack 捆绑应用程序.