Skip to content

Commit

Permalink
Download default audio track
Browse files Browse the repository at this point in the history
  • Loading branch information
reynaldichernando committed Dec 3, 2024
1 parent 788bce6 commit d60bec0
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions lib/youtube.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface FormatInfo {
width: number | null;
height: number | null;
quality: string | null;
audioIsDefault?: boolean;
}

export interface VideoInfo {
Expand All @@ -33,21 +34,24 @@ const RAW_INFO_SCHEMA = z.object({
shortDescription: z.string(),
}),
streamingData: z.object({
// formats: z.object({}).array(), // TODO
adaptiveFormats: z
.object({
itag: z.number(),
url: z.string(),
mimeType: z.string(),
width: z.number().optional(),
height: z.number().optional(),
// TODO: support undefined contentLength
contentLength: z
.string()
.refine((s) => s.match(/^\d+$/))
.transform(Number)
.optional(),
quality: z.string().optional(),
audioTrack: z.object({
displayName: z.string(),
id: z.string(),
audioIsDefault: z.boolean(),
}).optional(),
})
.array(),
}),
Expand Down Expand Up @@ -105,6 +109,7 @@ export async function fetchVideoInfo(videoId: string): Promise<VideoInfo> {
width: f.width ?? null,
height: f.height ?? null,
quality: f.quality ?? null,
audioIsDefault: f.audioTrack?.audioIsDefault,
})),
};
}
Expand Down Expand Up @@ -180,9 +185,15 @@ function findFormat(
return null;
}

return isVideo
? filtered[0]
: filtered.sort((a, b) => b.filesize! - a.filesize!)[0];
if (isVideo) {
return filtered[0];
} else {
const defaultTrack = filtered.find((f) => f.audioIsDefault);
if (defaultTrack) {
return defaultTrack;
}
return filtered.sort((a, b) => b.filesize! - a.filesize!)[0];
}
}

interface DownloadProgress {
Expand Down

0 comments on commit d60bec0

Please sign in to comment.