DEV Community

Cover image for Me and ChatGPT created a Bash script for text-to-speech using OpenAI TTS
Vladimir Ignatev
Vladimir Ignatev

Posted on

Me and ChatGPT created a Bash script for text-to-speech using OpenAI TTS

Hi Dev.to community!

ChatGPT became an essential helper in writing and analyzing a code. But this specific case makes ChatGPT incredibly helpful!

If you caught yourself crunching the Bash syntax to make a handy automation on your Linux or Mac, you should hire ChatGPT.

Just look at the output below! I asked GPT to create a text-to-speech Bash script that works similar to say command on Linux. It took just a minute to build this useful, flexible and beautiful CLI tool out of an idea.

#!/bin/bash
# Function to display help
usage() {
echo "Usage: $0 [-o output_file] [-v voice] [-m model] [-i input_file] \"input_string\""
exit 1
}
# Default values
output_file="speech.mp3"
voice="echo"
model="tts-1"
input_file=""
input_string=""
# Parse command-line options
while getopts 'o:v:m:i:h' flag; do
case "${flag}" in
o) output_file="${OPTARG}" ;;
v) voice="${OPTARG}" ;;
m) model="${OPTARG}" ;;
i) input_file="${OPTARG}" ;;
h) usage ;;
*) usage ;;
esac
done
# Check for remaining arguments
if [ -z "$input_file" ]; then
if [ $OPTIND -gt $# ]; then
echo "Error: Missing input string"
usage
else
input_string="${@:$OPTIND:1}"
fi
else
if [ -f "$input_file" ]; then
input_string=$(<"$input_file")
else
echo "Error: Input file does not exist"
exit 1
fi
fi
# Prepare parameters for OpenAI API call
PARAM=$(jq -n -c --arg model "$model" --arg voice "$voice" --arg input "$input_string" '$ARGS.named')
# Call OpenAI API to generate speech
curl https://api.openai.com/v1/audio/speech \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d "$PARAM" \
--output "$output_file"
view raw say.sh hosted with ❤ by GitHub

Quick tip: How to create a Bash/Python/etc. script using ChatGPT

  1. Start by asking to create a basic script. Do not provide details on what the script will do. Just tell more about script interface: CLI arguments, parameters, environmental variables etc.
  2. Tell ChatGPT apply necessary modifications and improvements to make this script do the actual workload. Provide sample code and ask to integrate some code pieces found over the web if needed.
  3. Well done!

Read the full story in Medium.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs