Youtube V3 API - Fetch a random video based on keyword

末鹿安然 提交于 2021-02-11 05:09:06

问题


I am using the below code to navigate to different pages of Youtube data.

I call the service again and again based on $randomNumber ( 1 to 20). But I don't think this is the better way.

 $youtube = new Google_Service_YouTube($client);

    $searchResponse = $youtube->search->listSearch('id,snippet', array(
        'type' => 'video',
        'q' => $searchTerm,
        'maxResults' => $videoCount
    ));

    $nextPage = $searchResponse["nextPageToken"];

    for($i=1;$i< $randomNumber ;$i++){

        $newSearchResponse = $youtube->search->listSearch('id,snippet', array(
            'q' => $searchTerm,
            'maxResults' => $videoCount,
            'type' => "video",
            'pageToken' => $nextPage
        ));

        $nextPage = $newSearchResponse["nextPageToken"];

    }

   return $newSearchResponse;

Please let me know how to get a random video based on the search text.


回答1:


Unfortunately there's no official way to get random videos with YouTube Data API.
Take a look at this question: How do I get a random YouTube video with the YouTube API?

I had a similar need, and i've "solved it" in a similar way to you: i made a few search->list requests to the API, with maxResults set to 50, (while keeping track of the video IDs) and then picked a random video from the resulting set.

This is not random at all, but I don't see any other way around the problem without having far too complex solutions.



来源:https://stackoverflow.com/questions/32063957/youtube-v3-api-fetch-a-random-video-based-on-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!