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

问题描述 投票:0回答:1

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

javascript youtube youtube-api youtube-data-api
1个回答
0
投票

这只是我这边的更新。

首先我们将获取该播放列表中的所有视频,然后对于每个视频,我们将发出 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;
© www.soinside.com 2019 - 2024. All rights reserved.