Created
July 17, 2025 14:26
-
-
Save htlin222/c06b24492652d839072a1ec9506dd0c1 to your computer and use it in GitHub Desktop.
A Bash script that reads a JSON input containing a message field, sends the message to OpenAI’s text-to-speech (TTS) API using a cheerful voice, and plays the resulting audio using afplay on macOS. Requires jq for JSON parsing and an OPENAI_API_KEY environment variable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # 讀取 JSON 輸入 | |
| json_input="$(cat)" | |
| # 擷取 message 欄位(需要 jq) | |
| message="$(echo "$json_input" | jq -r '.message')" | |
| # 如果 jq 或訊息抓不到,就退出 | |
| if [[ -z "$message" || "$message" == "null" ]]; then | |
| echo "Error: No valid message found in input JSON." >&2 | |
| exit 1 | |
| fi | |
| # 檢查必要環境變數 | |
| if [[ -z "$OPENAI_API_KEY" ]]; then | |
| echo "Error: OPENAI_API_KEY is not set." >&2 | |
| exit 2 | |
| fi | |
| # 設定 API 資訊 | |
| api_url="https://api.openai.com/v1/audio/speech" | |
| voice="coral" | |
| instructions="Speak in a cheerful and positive tone." | |
| # 播放機制(macOS) | |
| if command -v afplay >/dev/null 2>&1; then | |
| tmpfile="$(mktemp /tmp/speech.XXXXXX.mp3)" | |
| # 呼叫 OpenAI TTS API | |
| curl -s "$api_url" \ | |
| -H "Authorization: Bearer $OPENAI_API_KEY" \ | |
| -H "Content-Type: application/json" \ | |
| -d "{ | |
| \"model\": \"gpt-4o-mini-tts\", | |
| \"input\": \"$message\", | |
| \"voice\": \"$voice\", | |
| \"instructions\": \"$instructions\" | |
| }" -o "$tmpfile" | |
| # 播放音檔 | |
| afplay "$tmpfile" | |
| rm -f "$tmpfile" | |
| else | |
| echo "Error: 'afplay' not found. This script requires macOS." >&2 | |
| exit 3 | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment