MCPcopy Create free account
hub / github.com/TanStack/ai / toAudioFile

Function toAudioFile

packages/ai-grok/src/utils/audio.ts:13–108  ·  view source on GitHub ↗
(
  audio: string | File | Blob | ArrayBuffer,
  audioFormat?: string,
)

Source from the content-addressed store, hash-verified

11 * an `audioFormat` so we know what MIME type and extension to use.
12 */
13export function toAudioFile(
14 audio: string | File | Blob | ArrayBuffer,
15 audioFormat?: string,
16): File {
17 if (typeof File !== 'undefined' && audio instanceof File) {
18 // Prefer the caller-supplied `audioFormat` over a potentially empty or
19 // incorrect `File.type` — callers pass `audioFormat` precisely because
20 // they have more context than the browser does about the payload. If
21 // neither is set, fall through to the Blob-style error path below.
22 if (audioFormat) {
23 const mimeType = toMimeType(audioFormat)
24 return new File([audio], `audio.${extensionFor(mimeType)}`, {
25 type: mimeType,
26 })
27 }
28 if (audio.type) {
29 return audio
30 }
31 throw new Error(
32 'toAudioFile cannot infer type for File input with empty .type — pass an explicit audioFormat (e.g. "mp3", "wav", "audio/mpeg")',
33 )
34 }
35
36 if (typeof Blob !== 'undefined' && audio instanceof Blob) {
37 // Mirror the ArrayBuffer / bare-base64 paths: prefer the explicit
38 // audioFormat argument over the Blob's (often empty) .type. We refuse to
39 // fall back to `application/octet-stream` because that mislabels audio
40 // for the server.
41 const mimeType = audioFormat
42 ? toMimeType(audioFormat)
43 : audio.type || undefined
44 if (!mimeType) {
45 throw new Error(
46 'toAudioFile cannot infer type for Blob input with empty .type — pass an explicit audioFormat (e.g. "mp3", "wav", "audio/mpeg")',
47 )
48 }
49 return new File([audio], `audio.${extensionFor(mimeType)}`, {
50 type: mimeType,
51 })
52 }
53
54 if (audio instanceof ArrayBuffer) {
55 if (!audioFormat) {
56 throw new Error(
57 'toAudioFile cannot infer type for ArrayBuffer input — pass an explicit audioFormat (e.g. "mp3", "wav", "audio/mpeg")',
58 )
59 }
60 const mimeType = toMimeType(audioFormat)
61 return new File([audio], `audio.${extensionFor(mimeType)}`, {
62 type: mimeType,
63 })
64 }
65
66 if (typeof audio === 'string') {
67 if (audio.startsWith('data:')) {
68 const [header, base64Data] = audio.split(',')
69 // Fail loudly on malformed data: URIs instead of silently defaulting
70 // to `audio/mpeg` — the file's contract is that we never mislabel

Callers 2

transcribeMethod · 0.90

Calls 3

toMimeTypeFunction · 0.85
extensionForFunction · 0.85
base64ToArrayBufferFunction · 0.70

Tested by

no test coverage detected