0

Create voice

by
Published Apr 8, 2025

Create a personal (cloned) voice for the user

Script speechify Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Speechify = {
3
  token: string;
4
};
5
type Base64 = string;
6
/**
7
 * Create voice
8
 * Create a personal (cloned) voice for the user
9
 */
10
export async function main(
11
  auth: Speechify,
12
  body: {
13
    name: string;
14
    gender: "male" | "female" | "notSpecified";
15
    sample: {
16
      base64: Base64;
17
      type:
18
        | "image/png"
19
        | "image/jpeg"
20
        | "image/gif"
21
        | "application/pdf"
22
        | "appication/json"
23
        | "text/csv"
24
        | "text/plain"
25
        | "audio/mpeg"
26
        | "audio/wav"
27
        | "video/mp4";
28
      name: string;
29
    };
30
    avatar?: {
31
      base64: Base64;
32
      type:
33
        | "image/png"
34
        | "image/jpeg"
35
        | "image/gif"
36
        | "application/pdf"
37
        | "appication/json"
38
        | "text/csv"
39
        | "text/plain"
40
        | "audio/mpeg"
41
        | "audio/wav"
42
        | "video/mp4";
43
      name: string;
44
    };
45
    consent: string;
46
  },
47
) {
48
  const url = new URL(`https://api.sws.speechify.com/v1/voices`);
49

50
  const formData = new FormData();
51
  for (const [k, v] of Object.entries(body)) {
52
    if (v !== undefined && v !== "") {
53
      if (["sample", "avatar"].includes(k)) {
54
        const { base64, type, name } = v as {
55
          base64: Base64;
56
          type: string;
57
          name: string;
58
        };
59
        formData.append(
60
          k,
61
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
62
            type,
63
          }),
64
          name,
65
        );
66
      } else {
67
        formData.append(k, String(v));
68
      }
69
    }
70
  }
71
  const response = await fetch(url, {
72
    method: "POST",
73
    headers: {
74
      Authorization: "Bearer " + auth.token,
75
    },
76
    body: formData,
77
  });
78
  if (!response.ok) {
79
    const text = await response.text();
80
    throw new Error(`${response.status} ${text}`);
81
  }
82
  return await response.text();
83
}
84