Skip to content

Audio

Text-to-speech

bash
curl https://api.fastapi.ai/v1/audio/speech \
  -H "Authorization: Bearer $FAST_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o-mini-tts",
    "input": "Hello",
    "voice": "alloy"
  }' \
  --output speech.mp3
javascript
import fs from "node:fs";

const res = await fetch("https://api.fastapi.ai/v1/audio/speech", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.FAST_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ model: "gpt-4o-mini-tts", input: "Hello", voice: "alloy" }),
});

if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);

const arrayBuffer = await res.arrayBuffer();
fs.writeFileSync("speech.mp3", Buffer.from(arrayBuffer));
python
import os
import requests

resp = requests.post(
  "https://api.fastapi.ai/v1/audio/speech",
  headers={
    "Authorization": f"Bearer {os.environ['FAST_API_KEY']}",
    "Content-Type": "application/json",
  },
  json={"model": "gpt-4o-mini-tts", "input": "Hello", "voice": "alloy"},
)

with open("speech.mp3", "wb") as f:
  f.write(resp.content)
go
package main

import (
  "bytes"
  "encoding/json"
  "io"
  "net/http"
  "os"
)

func main() {
  payload := map[string]any{
    "model": "gpt-4o-mini-tts",
    "input": "Hello",
    "voice": "alloy",
  }
  b, _ := json.Marshal(payload)

  req, _ := http.NewRequest("POST", "https://api.fastapi.ai/v1/audio/speech", bytes.NewReader(b))
  req.Header.Set("Authorization", "Bearer "+os.Getenv("FAST_API_KEY"))
  req.Header.Set("Content-Type", "application/json")

  resp, err := http.DefaultClient.Do(req)
  if err != nil {
    panic(err)
  }
  defer resp.Body.Close()

  data, _ := io.ReadAll(resp.Body)
  _ = os.WriteFile("speech.mp3", data, 0o644)
}
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
  public static void main(String[] args) throws Exception {
    String body = "{\"model\":\"gpt-4o-mini-tts\",\"input\":\"Hello\",\"voice\":\"alloy\"}";

    HttpRequest req = HttpRequest.newBuilder()
      .uri(URI.create("https://api.fastapi.ai/v1/audio/speech"))
      .header("Authorization", "Bearer " + System.getenv("FAST_API_KEY"))
      .header("Content-Type", "application/json")
      .POST(HttpRequest.BodyPublishers.ofString(body))
      .build();

    HttpResponse<byte[]> resp = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofByteArray());
    Files.write(Path.of("speech.mp3"), resp.body());
  }
}

那年我双手插兜, 让bug稳如老狗