我正在使用 YouTube Data API v3,有什么方法可以获得播放列表的总持续时间

发布于 2025-01-14 17:01:49 字数 63 浏览 4 评论 0原文

我想使用 JavaScript 或 TypeScript 获取播放列表的总持续时间以及播放列表中存在的视频总数。

I want to get the total duration of the playlist and also the total number of videos present inside the playlist, using JavaScript or TypeScript.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自由如风 2025-01-21 17:01:49

这只是我这边的更新。

首先,我们将获取该播放列表中的所有视频,然后对于每个视频,我们将发出 50 个视频 ID 的组合请求(每个请求),然后添加持续时间。

这是我的 nextjs API(项目)中的一个示例。

import convertISO8601ToSeconds from '@lib/ISO8601ToSeconds';
import type { NextApiRequest, NextApiResponse } from 'next';
import PlaylistResponse, { Item, FinalItem } from 'types/playlist/items';
import videoResponse, { VideoItem } from 'types/videos/response';

type Data = {
    success: boolean;
    data?: {
        videos: Array<FinalItem>,
        length: number,
        totalDuration: number
    };
    error?: string;
};

const handler: Function = async (req: NextApiRequest, res: NextApiResponse<Data>) => {
    const { query } = req;
    var videos: Array<Item> = [];
    var finalVideosResponse: Array<FinalItem> = [];
    var videosIds: Array<string> = [];
    var temp: Array<string> = [];
    var totalDuration: number = 0;

    const getMaxVideos: Function = async (pageToken: string, playlistId: string): Promise<void> => {
        const response: PlaylistResponse = await fetch(`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&pageToken=${pageToken}&playlistId=${playlistId}&maxResults=50&key=${apikey}`, {
            headers: {
                "Content-Type": "application/json"
            },
            method: "GET"
        }).then(res => res.json());

        if (response.items)
            videos.push(...response.items);

        if (response.nextPageToken)
            await getMaxVideos(response.nextPageToken, playlistId);
    }

    const getMaxVideoResponse: Function = async (ids: Array<string>): Promise<void> => {
        const videosResponse: videoResponse = await fetch(`https://youtube.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=${ids[0]}&key=${apikey}`, {
            headers: {
                "Content-Type": "application/json"
            },
            method: "GET"
        }).then(res => res.json());

        if (videosResponse.items) {
            videosResponse.items.map((value: VideoItem, index: number) => {
                const secs: number = convertISO8601ToSeconds(value.contentDetails.duration);
                totalDuration += secs;

                finalVideosResponse.push({
                    duration: secs,
                    title: value.snippet.title,
                    videoId: value.id
                });
            });
        }

        if (ids[1]) {
            ids.shift();
            await getMaxVideoResponse(ids);
        }
    }

    try {
        if (query.playlistId) {
            try {
                await getMaxVideos("", query.playlistId);
            } catch (error) {
                throw (error instanceof Error) ? error.message : "Something Wrong - getting playlist items.";
            }

            if (videos.length > 0) {
                videos.map((value: Item, index: number) => {
                    temp.push(value.snippet.resourceId.videoId);

                    if ((temp.length % 50 === 0) || (index + 1 === videos.length)) {
                        videosIds.push(temp.toString());
                        temp = [];
                    }
                });
            }

            if (videosIds.length > 0) {
                try {
                    await getMaxVideoResponse(videosIds);
                } catch (error) {
                    throw (error instanceof Error) ? error.message : "Something Wrong - getting individual videos.";
                }

                res.json({
                    success: true,
                    data: {
                        videos: finalVideosResponse,
                        length: finalVideosResponse.length,
                        totalDuration: totalDuration
                    }
                });
            }
        }

        else throw "PlaylistId Missing";
    } catch (error) {
        res.json({ success: false, error: (error instanceof Error) ? error.message : "Something Wrong" });
    }
}

export default handler;

This is an update from my side only.

here first we'll get all the videos inside that playlist then for every video we'll make a combined request of 50 video ids (per request) and then we'll add the duration.

here is an example from my nextjs API (project).

import convertISO8601ToSeconds from '@lib/ISO8601ToSeconds';
import type { NextApiRequest, NextApiResponse } from 'next';
import PlaylistResponse, { Item, FinalItem } from 'types/playlist/items';
import videoResponse, { VideoItem } from 'types/videos/response';

type Data = {
    success: boolean;
    data?: {
        videos: Array<FinalItem>,
        length: number,
        totalDuration: number
    };
    error?: string;
};

const handler: Function = async (req: NextApiRequest, res: NextApiResponse<Data>) => {
    const { query } = req;
    var videos: Array<Item> = [];
    var finalVideosResponse: Array<FinalItem> = [];
    var videosIds: Array<string> = [];
    var temp: Array<string> = [];
    var totalDuration: number = 0;

    const getMaxVideos: Function = async (pageToken: string, playlistId: string): Promise<void> => {
        const response: PlaylistResponse = await fetch(`https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&pageToken=${pageToken}&playlistId=${playlistId}&maxResults=50&key=${apikey}`, {
            headers: {
                "Content-Type": "application/json"
            },
            method: "GET"
        }).then(res => res.json());

        if (response.items)
            videos.push(...response.items);

        if (response.nextPageToken)
            await getMaxVideos(response.nextPageToken, playlistId);
    }

    const getMaxVideoResponse: Function = async (ids: Array<string>): Promise<void> => {
        const videosResponse: videoResponse = await fetch(`https://youtube.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id=${ids[0]}&key=${apikey}`, {
            headers: {
                "Content-Type": "application/json"
            },
            method: "GET"
        }).then(res => res.json());

        if (videosResponse.items) {
            videosResponse.items.map((value: VideoItem, index: number) => {
                const secs: number = convertISO8601ToSeconds(value.contentDetails.duration);
                totalDuration += secs;

                finalVideosResponse.push({
                    duration: secs,
                    title: value.snippet.title,
                    videoId: value.id
                });
            });
        }

        if (ids[1]) {
            ids.shift();
            await getMaxVideoResponse(ids);
        }
    }

    try {
        if (query.playlistId) {
            try {
                await getMaxVideos("", query.playlistId);
            } catch (error) {
                throw (error instanceof Error) ? error.message : "Something Wrong - getting playlist items.";
            }

            if (videos.length > 0) {
                videos.map((value: Item, index: number) => {
                    temp.push(value.snippet.resourceId.videoId);

                    if ((temp.length % 50 === 0) || (index + 1 === videos.length)) {
                        videosIds.push(temp.toString());
                        temp = [];
                    }
                });
            }

            if (videosIds.length > 0) {
                try {
                    await getMaxVideoResponse(videosIds);
                } catch (error) {
                    throw (error instanceof Error) ? error.message : "Something Wrong - getting individual videos.";
                }

                res.json({
                    success: true,
                    data: {
                        videos: finalVideosResponse,
                        length: finalVideosResponse.length,
                        totalDuration: totalDuration
                    }
                });
            }
        }

        else throw "PlaylistId Missing";
    } catch (error) {
        res.json({ success: false, error: (error instanceof Error) ? error.message : "Something Wrong" });
    }
}

export default handler;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文