ブログ

PowerShellからIBM Watson Speech to Text / Text to Speech を使ってみた

初めに

PowerShellからIBM Watson Speech to Text および Text to Speech のAPIを呼び出して、音声認識、人工音声作成をしてみたので、その結果をご紹介いたします。

前提

IBM Cloud にて、Watson Speeh to Text および Text to Speech のサービスを作成済みであること

参考情報

IBM Cloud API Docs
Speech to Text : https://cloud.ibm.com/apidocs/speech-to-text
Text to Speech : https://cloud.ibm.com/apidocs/text-to-speech

Speech to Text の実行

上記参考資料を参照すると以下のような実行サンプル例があります。

curl -X POST -u "apikey:{apikey}" --header "Content-Type: audio/flac" --data-binary @audio-file2.flac "{url}/v1/recognize?word_alternatives_threshold=0.9&keywords=colorado%2Ctornado%2Ctornadoes&keywords_threshold=0.5"

これを参考に、PowerShellのRestAPIを呼び出す、「Invoke-RestMethod」を使用すると以下のようになります。
{apikey}と{url}は、サービスの資格情報の実際の値に置き換えてください。
auido-file2.flacは、https://watson-developer-cloud.github.io/doc-tutorial-downloads/speech-to-text/reference/audio-file2.flac からダウンロード可能です。
ポイントは、3行目、4行目で、認証情報をCredetialオブジェクトに変換し、Invoke-RestMethodのCredentialオプションで指定しているところになります。

$user = "apikey"
$pass = "{apikey}"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$endPoint = "{url}"
$audioFile = "audio-file2.flac"
$result = Invoke-RestMethod -Method POST -Credential $cred -Headers @{"Content-Type"="audio/flac"} -InFile $audioFile -Uri "$($endPoint)/v1/recognize?word_alternatives_threshold=0.9&keywords=colorado%2Ctornado%2Ctornadoes&keywords_threshold=0.5"
$result.results | ForEach-Object {Write-Host $_.alternatives.transcript}

実行結果は、以下のようになります。

a line of severe thunderstorms with several possible tornadoes is approaching Colorado on Sunday

Text to Speech の実行

上記参考資料を参照すると以下のような実行サンプル例があります。

curl -X POST -u "apikey:{apikey}" --header "Content-Type: application/json" --header "Accept: audio/wav" --data "{\"text\":\"Hello world\"}" --output hello_world.wav "{url}/v1/synthesize?voice=en-US_AllisonV3Voice"

これを参考に、PowerShellのRestAPIを呼び出す、「Invoke-RestMethod」を使用すると以下のようになります。
{apikey}と{url}は、サービスの資格情報の実際の値に置き換えてください。
ポイントは、Speech to Text と同様に、3行目、4行目で、認証情報をCredetialオブジェクトに変換し、Invoke-RestMethodのCredentialオプションで指定しているところになります。
また、6行目から8行目で、音声に変換したい文字列を、ハッシュテーブルをJSONに変換し、さらにutf8にエンコードして、Invoke-RestMethodのBodyオプションで指定しているところになります。

$user = "apikey"
$pass = "{apikey}"
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$endPoint = "{url}"
$body = @{"text"="Hello world"}
$jsonData = $body | ConvertTo-Json
$utf8JsonData = [System.Text.Encoding]::UTF8.GetBytes($JsonData)
$audioFile = "hello_world.wav"
Invoke-RestMethod -Method Post -Credential $cred -Headers @{"Content-Type"="application/json"; "Accept"="audio/wav"} -Body $utf8JsonData -OutFile $audioFile -Uri "$($endPoint)/v1/synthesize?voice=en-US_AllisonV3Voice"

実行結果は、Hello worldと発言された音声ファイル「hello_world.wav」が生成されます。

pagetop