LoginSignup
1
0

More than 3 years have passed since last update.

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

Posted at

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

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

const AWS = require('aws-sdk');
const speech = require('@google-cloud/speech').v1p1beta1;
const client = new speech.SpeechClient();

const s3 = new AWS.S3({
    apiVersion: '2012-09-25'
});

exports.handler = function(event, context) {

    const bucket = event.Records[0].s3.bucket.name;
    const key = event.Records[0].s3.object.key;
    const params = {
        Bucket: bucket,
        Key: key
    };
    s3.getObject(params, async (err, data) => {
        if (err) {
            console.log(err, err.stack);
        } else {
            const audioBytes = data.Body.toString('base64');
            const audio = { content: audioBytes };
            const config = {
                encoding: 'MP3',
                sampleRateHertz: 44100,
                languageCode: 'ja-JP',
            };
            const request = {
                audio: audio,
                config: config,
            };

            const [response] = await client.recognize(request);
            const transcription = response.results.map(result => result.alternatives[0].transcript).join('\n');
            console.log(transcription);
        };
    });
}

ポイント

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

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

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

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

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

const [response] = await client.recognize(request);

3. sampleRateHertzの調整

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

結果

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

最後に

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

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0