Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

S3に保存されたMP3ファイルをLambdaでGoogle Cloud Speech-to-Textを使って文字起こしする

$
0
0

S3に保存されたMP3ファイルをLambdaでGoogle Cloud Speech-to-Textを使って文字起こしする

はじめに

前回のS3に保存されたwavファイルをLambdaでGoogle Cloud Speech-to-Textを使って文字起こしするに引き続き、
今回はMP3ファイルを対象に、S3に保存されたMP3ファイルをLambdaでGoogle Cloud Speech-to-Textを使って文字起こしする手順をまとめます。

重複する点が非常に多いので、相違点になるコードの部分だけ(前回でいう5-9のみ)ご紹介します。

Code

実行するコードは以下になります。

constAWS=require('aws-sdk');constspeech=require('@google-cloud/speech').v1p1beta1;constclient=newspeech.SpeechClient();consts3=newAWS.S3({apiVersion:'2012-09-25'});exports.handler=function(event,context){constbucket=event.Records[0].s3.bucket.name;constkey=event.Records[0].s3.object.key;constparams={Bucket:bucket,Key:key};s3.getObject(params,async(err,data)=>{if(err){console.log(err,err.stack);}else{constaudioBytes=data.Body.toString('base64');constaudio={content:audioBytes};constconfig={encoding:'MP3',sampleRateHertz:44100,languageCode:'ja-JP',};constrequest={audio:audio,config:config,};const[response]=awaitclient.recognize(request);consttranscription=response.results.map(result=>result.alternatives[0].transcript).join('\n');console.log(transcription);};});}

ポイント

1. Cloud Speech-to-TextをMPx3で使うにはβ版を使う

音声エンコードの概要に記されている通り、MP3ファイルの場合はベータ版のみが使用できます。 なので2行目に変更があります。

constspeech=require('@google-cloud/speech').v1p1beta1;

2. async/awaitで非同期処理対策

認識をしているときに、非同期で処理が行われてしまいうまく文字起こしできない可能性があるので、前回は入れなかったasync/awaitを入れてその対策をしました

const[response]=awaitclient.recognize(request);

3. sampleRateHertzの調整

お好みのツールを使ってsampleRateHertzを確認して調整していただければと。もしかしらこのパラメータ設定しなくても行けるかもしれません。

結果

transcriptionの中に入っています。個人的には結構な認識精度で驚いています。

最後に

今回は、前回の記事に続いて、MP3のデータを扱ってみました。
正直、JavaScript、Node.jsを雰囲気でやってる人間なので間違いなどあったらぜひ教えていただきたいです。

参考


Viewing all articles
Browse latest Browse all 8691

Trending Articles