Skip to content

Instantly share code, notes, and snippets.

@pschichtel
Created October 23, 2020 17:59
Show Gist options
  • Save pschichtel/5b97382c4b3e0e234270ee6066897cf2 to your computer and use it in GitHub Desktop.
Save pschichtel/5b97382c4b3e0e234270ee6066897cf2 to your computer and use it in GitHub Desktop.
Small bash script that synthesizes text to speech using Google's services. The script expects the gcloud CLI tool, curl and jq installed in the path.
#!/usr/bin/env bash
voice="${1?no voice given!}"
gender="${2?no gender given!}"
text="${3?no text given!}"
file_name="${4:-"-"}"
access_token="$(gcloud auth application-default print-access-token)"
if echo "$text" | grep -q "<speak>"
then
input="ssml"
else
input="text"
fi
read -d '' data <<EOL
{
"input": {
"${input}": "${text}"
},
"voice": {
"languageCode": "de-DE",
"name": "${voice}",
"ssmlGender": "${gender}"
},
"audioConfig": {
"audioEncoding": "MP3"
}
}
EOL
endpoint="https://texttospeech.googleapis.com/v1/text:synthesize"
response_file="$(mktemp)"
exec 3>"$response_file"
status="$(
curl -k -o "/dev/fd/3" -s -w '%{http_code}' \
-H "Authorization: Bearer ${access_token}" \
-H "Content-Type: application/json; charset=utf-8" \
--data "${data}" \
"$endpoint"
)"
exec 3>&-
response="$(< "$response_file")"
rm "$response_file"
if [ "$status" = "200" ]
then
encoded_audio_content="$(echo "$response" | jq -r .audioContent)"
if [ "$file_name" = "-" ]
then
echo -n "$encoded_audio_content" | base64 -d -
else
echo -n "$encoded_audio_content" | base64 -d - > "$file_name"
fi
else
echo "Synthesis request failed! HTTP status: ${status}"
echo "Response:"
echo $response
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment