C# 如何使用 YouTube API 获取随机的 YouTube 视频?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11315416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:22:36  来源:igfitidea点击:

How do I get a random YouTube video with the YouTube API?

c#.netyoutube-apiyoutube.net-api

提问by b0x0rz

I need a way of getting a completelyrandom YouTube video. No restriction.

我需要一种获取完全随机的 YouTube 视频的方法。没有限制。

How can I do with with the YouTube API?

如何使用 YouTube API?

** edit * OK as requested here is what i tried so far:

** 编辑 * 在这里按要求确定是我到目前为止所尝试的:

1 - went through the api and examples at youtube dev site. http://www.youtube.com/dev/no luck finding the correct api or a way of doing it there.

1 - 浏览了 youtube 开发站点上的 api 和示例。http://www.youtube.com/dev/没有找到正确的 api 或在那里做的方法。

2 - google search of course ;) got http://randomyoutubevideo.net/but they only offer an api from THEM to use in between me and youtube. < this gives me hope that it IS actually possible to do this.

2 - 当然是谷歌搜索;) 得到了http://randomyoutubevideo.net/但他们只提供他们的 api 以在我和 youtube 之间使用。<这给了我希望实际上可以做到这一点。

3 - even checked the youtube app gallery http://youtube-gallery.appspot.com/to see if anyone is doing it. and HOW.

3 - 甚至检查了 youtube 应用程序库http://youtube-gallery.appspot.com/看看是否有人在这样做。如何。

what i will also do is ask on the youtube discussion pages. perhaps someone there can help.

我还会做的是在 youtube 讨论页面上提问。也许那里有人可以提供帮助。

采纳答案by N_A

There appears to be no way to do this, however there are ways to approximate what you're looking for. See herefor ideas.

似乎没有办法做到这一点,但是有一些方法可以近似您正在寻找的内容。看到这里的想法。

The basic ideas from those pages are to use the most recent uploads feed (if you don't care about when something was uploaded) or simply get a dump of ALL youtube videos and randomly select a URL from those.

这些页面的基本想法是使用最近上传的提要(如果您不关心什么时候上传)或者只是获取所有 youtube 视频的转储并从中随机选择一个 URL。

To quote the youtube API guy in first link:

在第一个链接中引用 youtube API 人:

As others have mentioned, we make any data dumps or the like available. All your interaction with YouTube needs to be done via the standard API.

I can't say that I have enough of a background in statistics to suggest how you could retrieve a truly random sample of videos. I do think that going about it by attempting to generate 11 character YouTube video ids is probably the wrong approach, though—there are just too many non-existent video ids that you'll bump up against, and I don't think the best use of the API is to make requests that will return HTTP 404 responses X% of the time.

You might have better luck just using the API to search for words or phrases that are picked at "random" and taking a sampling of the results. If you do that, you should think about what value to use for the orderby= URL parameter. The default ordering is "relevance", which will lead to the top results being the ones that our algorithms think are the most relevant to your search terms. This might skew your results if you always grab the first entry or the like. You could also order by "published" which will give you a reverse-chronological feed of videos.

Cheers, -Jeff Posnick, YouTube API Team as With regards to randomyoutubevideo.net, this is what the "About" page of that site has to say:

So how can we provide truly random links to YouTube videos? It turns out that the YouTube programming interface (API) provides additional functions that allow the discovery of videos that are much more random. Using a number of tricks, combined with a little manipulation of the space-time frabric, we have managed to create a process that yiields truly random links to YouTube videos.

The random YouTube function on this page currently uses a subset of the database. Over time we will expand this database and, depending on demand, may make it available free of charge via an API.

正如其他人所提到的,我们提供任何数据转储等。您与 YouTube 的所有互动都需要通过标准 API 完成。

我不能说我有足够的统计学背景来建议您如何检索真正随机的视频样本。我确实认为通过尝试生成 11 个字符的 YouTube 视频 ID 可能是错误的方法,但是,您会遇到太多不存在的视频 ID,我认为这不是最好的API 的用途是发出将在 X% 的时间内返回 HTTP 404 响应的请求。

仅使用 API 来搜索“随机”挑选的单词或短语并对结果进行抽样,您可能会获得更好的运气。如果这样做,您应该考虑为 orderby= URL 参数使用什么值。默认排序是“相关性”,这将导致我们的算法认为与您的搜索词最相关的结果是最重要的。如果您总是抓取第一个条目或类似内容,这可能会扭曲您的结果。您还可以按“已发布”进行订购,这将为您提供按时间倒序排列的视频。

干杯,-Jeff Posnick,YouTube API 团队关于 randomyoutubevideo.net,这是该网站的“关于”页面必须说的:

那么我们如何才能提供真正随机的 YouTube 视频链接呢?事实证明,YouTube 编程接口 (API) 提供了额外的功能,允许发现更加随机的视频。使用一些技巧,结合对时空结构的一点点操作,我们已经成功地创建了一个过程,产生真正随机的 YouTube 视频链接。

此页面上的随机 YouTube 功能目前使用数据库的一个子集。随着时间的推移,我们将扩展此数据库,并可能根据需求通过 API 免费提供。

I understand this to mean that they have been pulling large lists of videos from the API and making a DB of them from which they randomly select.

我理解这意味着他们一直在从 API 中提取大量视频并制作他们从中随机选择的数据库。

回答by Anton Anders

The best way to get random video IDs is to generate your own Database. Use the VideoSearch-Request of Google's Youtube-API. Just generate a searchquery like "v=SEARCH_STRING" and insert the videoids you get into your Database. The searchstring should be a randomly generated string. I found out, that a lenght of the string should be 4 chars to get most Videos out of a Request without having to many repeating Results.

获取随机视频 ID 的最佳方法是生成您自己的数据库。使用 Google 的 Youtube-API 的 VideoSearch-Request。只需生成一个像“v=SEARCH_STRING”这样的搜索查询,然后将您获得的 videoid 插入到您的数据库中。searchstring 应该是随机生成的字符串。我发现,字符串的长度应该是 4 个字符,这样才能从请求中获取大多数视频,而无需多次重复结果。

If your Database is ready, you can just get a random row out of it.

如果您的数据库已准备就绪,您可以从中随机获取一行。

I've done this on my own Website(random-video.net)and got over 2 million entrys in a few hours. There are no real limitations-just the size of your Database.

我已经在我自己的网站(random-video.net)上完成了这项工作,并在几个小时内获得了超过 200 万个条目。没有真正的限制——只是你的数据库的大小。

回答by ZeDuS

Is a dirty crawler an option? Because I've used a simple random youtube vid link generator. It was only for accumulating a big db of videos, not for production.
It seems to be (very) similar to "youtuberandomvideo.com" approach as he described.

肮脏的爬虫是一种选择吗?因为我使用了一个简单的随机 youtube vid 链接生成器。它只是为了积累大量的视频,而不是用于制作。
它似乎(非常)类似于他所描述的“youtuberandomvideo.com”方法。

import re, urllib
from random import randint

def random_str(str_size):
    res = ""
    for i in xrange(str_size):
        x = randint(0,25)
        c = chr(ord('a')+x)
        res += c
    return res

def find_watch(text,pos):
    start = text.find("watch?v=",pos)
    if (start<0):
        return None,None
    end = text.find(" ",start)
    if (end<0):
        return None,None

    if (end-start > 200): #silly heuristics, probably not a must
        return None,None

    return text[start:end-1], start


def find_instance_links():
    base_url = 'https://www.youtube.com/results?search_query='
    url = base_url+random_str(3)
    #print url

    r = urllib.urlopen(url).read()

    links = {}

    pos = 0
    while True:
        link,pos =  find_watch(r,pos)
        if link == None or pos == None:
            break
        pos += 1
        #print link
        if (";" in link):
            continue
        links[link] = 1

    items_list = links.items()

    list_size = len(items_list)
    selected = randint(list_size/2,list_size-1)
    return items_list[selected][0]


for i in xrange(1000):
    link = find_instance_links()
    print link

As you can see it's fairly simplistic and could probably break easily, but IIRC I managed to quickly get thousands of random video links which was all that I needed, and it's only few lines of code...

正如您所看到的,它相当简单,可能很容易损坏,但是 IIRC 我设法快速获得了数千个随机视频链接,这正是我所需要的,而且只有几行代码......

Some explanation of the code: (random->pseudo random ...)
1. Random generation of search queries (3 letters long here)
2. Randomly selecting some link from the bottom half of the video links (the motivation was to avoid commercials)

代码的一些解释:(随机->伪随机...)
1. 随机生成搜索查询(这里长 3 个字母)
2. 从视频链接的下半部分随机选择一些链接(动机是为了避免广告)

Note:The code is messy - it should only serve as a basic example of the technique, not of proper code design and/or elegant python code.

注意:代码很乱 - 它应该只作为技术的基本示例,而不是正确的代码设计和/或优雅的 Python 代码。

回答by phil294

AFAIK: Searching for v=has no meaningful effect. iI you search for v=LadyGaga, you'll find Lady Gaga videos. YouTube's search algorithm looks through description, title, etc. - if a video has another video linked in its description (aka a ?v=..), it is more likely to come up with this search request. Also see https://developers.google.com/youtube/v3/docs/search/list.

AFAIK:搜索v=没有有意义的效果。iI 你搜索v=LadyGaga,你会找到 Lady Gaga 的视频。YouTube 的搜索算法会查看描述、标题等 - 如果视频在其描述中链接了另一个视频(又名?v=..),则更有可能提出此搜索请求。另请参阅https://developers.google.com/youtube/v3/docs/search/list

There is no random pick implemented yet in Google's Youtube Data API. What I did was querying

Google 的 Youtube Data API 中还没有实现随机选择。我所做的是查询

https://www.googleapis.com/youtube/v3/search?part=id&maxResults=50&type=video&q=QUERYSTRING&key=KEY

, with QUERYSTRINGbeing a random 5-character string in video-ID syntax. If the result set contains between 1 and 50 videos, of which at least one id contains the string, a random video was found. This method usually takes 1-5 tries.

QUERYSTRING在 video-ID 语法中是一个随机的 5 个字符的字符串。如果结果集包含 1 到 50 个视频,其中至少有一个 id 包含字符串,则发现随机视频。此方法通常需要尝试 1-5 次。

The last check is needed. Example: A random string was ydoat. Querying this with the above url results in only one video with the id VEBt0Hxp5Q8, which does not fit. The video probably contains the string in its description somewhere. If I search for ydoatvia https://www.youtube.com/results?q=ydoat, no result is found. Searching for v%3Dydoat(v=ydoat) leads to the same results.

需要最后一次检查。示例:一个随机字符串是ydoat。用上面的 url 查询这个结果只会得到一个带有 id 的视频VEBt0Hxp5Q8,它不适合。该视频可能在某处的描述中包含该字符串。如果我搜索ydoatvia https://www.youtube.com/results?q=ydoat,则找不到任何结果。搜索v%3Dydoat( v=ydoat) 会得到相同的结果。

edit. source in php: https://github.com/phil294/-Php-Randomtube-random-YouTube-video-generator-

编辑。php 来源:https: //github.com/phil294/-Php-Randomtube-random-YouTube-video-generator-

Like Anton, I found 4 random characters will be best fitting.

像安东一样,我发现 4 个随机字符最合适。

回答by osanger

Step 1: Create API-Key

第 1 步:创建 API-Key

  1. Create a google-Account
  2. Visit: https://console.developers.google.com/
  3. Create a new project: Click on Create new Project in head-menu and give it a name
  4. Now Activate the YoutTubeData API: Click it and enable it.
  5. Insert your Applications-Infos
  6. Click "create Credentials"
  7. Klick what do i need?
  8. Note your API-Key
  1. 创建一个谷歌账户
  2. 访问:https: //console.developers.google.com/
  3. 创建一个新项目:点击主菜单中的创建新项目并为其命名
  4. 现在激活 YoutTubeData API:单击它并启用它。
  5. 插入您的应用程序信息
  6. 点击“创建凭据”
  7. 点击我需要什么?
  8. 记下您的 API 密钥

Now you can access the YouTube-API.

现在您可以访问 YouTube-API。

Step 2: Use YouTube-API to crawl Videos

第 2 步:使用 YouTube-API 抓取视频

In this step we use the YouTube-API to get random VideoId's. With the following Code-Samples you will get 50 random Apis from the YouTube-Search. That's the maximum. You can store them in a DB or return a random ID directly.

在这一步中,我们使用 YouTube-API 来获取随机 VideoId。使用以下代码示例,您将从 YouTube 搜索中获得 50 个随机的 API。那是最大值。您可以将它们存储在数据库中或直接返回一个随机 ID。

Attention: There is a limit of 30,000 units/second/user and 1,000,000 per day.

注意: 有 30,000 个单位/秒/用户和每天 1,000,000 个的限制。

Codesamples

代码示例



[C#-Example]

[C#-示例]

using System;
using System.Linq;
using System.Net;
using Newtonsoft.Json;

namespace YouTube
{
   class Program
   {
    private static Random random = new Random();

    public static string RandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }

    static void Main(string[] args)
    {
        var count = 50;
        var API_KEY = "YOUR KEY";
        var q = RandomString(3);
        var url = "https://www.googleapis.com/youtube/v3/search?key=" + API_KEY + "&maxResults="+count+"&part=snippet&type=video&q=" +q;

        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString(url);
            dynamic jsonObject = JsonConvert.DeserializeObject(json);
            foreach (var line in jsonObject["items"])
            {
                Console.WriteLine(line["id"]["videoId"]);
                /*store your id*/
            }
            Console.Read();
        }
    }
}
}

[PHP-Example]

[PHP-示例]

function crawlVideos($count = 50)
{
    $q = $this->generateRandomString(3);
    $url = "https://www.googleapis.com/youtube/v3/search?key=" . self::API_KEY . "&maxResults=$count&part=snippet&type=video&q=" . $q;
    $JSON = file_get_contents($url);
    $JSON_Data_search = json_decode($JSON);
    foreach ($JSON_Data_search->{"items"} as $result) {
        $videoId = ($result->{"id"}->{"videoId"});
        /*Insert video to your database*/
    }
}

function generateRandomString($length = 10)
{
    return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}

[Python-Example]

[Python-示例]

import json
import urllib.request
import string
import random

count = 50
API_KEY = 'your_key'
random = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(3))

urlData = "https://www.googleapis.com/youtube/v3/search?key={}&maxResults={}&part=snippet&type=video&q={}".format(API_KEY,count,random)
webURL = urllib.request.urlopen(urlData)
data = webURL.read()
encoding = webURL.info().get_content_charset('utf-8')
results = json.loads(data.decode(encoding))

for data in results['items']:
    videoId = (data['id']['videoId'])
    print(videoId)
    #store your ids

Step 3: Generate/Return your Video-URL

第 3 步:生成/返回您的视频 URL

Now read a random ID from database like:

现在从数据库中读取一个随机 ID,如:

SELECT 'id' 
FROM yttable
WHERE 1 ORDER BY RAND() LIMIT 1

Your random video is:

您的随机视频是:

https://www.youtube.com/embed/[random ID]

Have fun!

玩得开心!

回答by Deyan Yosifov

I know it's a little bit off-topic but I can offer the following bash script. I use it on my Raspberry Pi and it works quite well.

我知道这有点离题,但我可以提供以下 bash 脚本。我在我的 Raspberry Pi 上使用它,效果很好。

    #!/bin/sh
    while [ true ];
    do
    searchresult=""
    while [ -z "$searchresult" ]; do
    rand=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-5};echo)
    echo "$rand"
    searchresult=$(googler -C -n 100 --np -x -w https://www.youtube.com "$rand")
    done
    urls=$(echo "$searchresult" | grep -o "https://www.youtube.com/watch?v=...........")
    url=$(shuf -e -n 1 $urls)
    echo "$url"
    omxplayer -o hdmi $(youtube-dl -f mp4 -g "$url")
    done

Prerequisites are that you have installed googlerand youtube-dl. My initial idea was to generate random 11 character strings and to append them to the base URL for YouTube videos. However, the number of possible permutations is enormous (26 capital letters + 26 small letters + 10 digits + hyphen + underscore = 64 characters; 64^11=7.38x10^19 permutations) and will be used up if every person on the Earth uploads 10 billion videos. That's why randomly generating the complete 11-character identifier is not a practicable approach. My script generates random 5-character strings instead (variable "rand") and passes them as a search query to googler. Googler searches the YouTube site for these random strings and in most cases it returns results (variable "searchresult"). In case there is no result, the search is repeated with another random string and so on till success. Usually it takes one to three tries. I tried with different lengths of the search string - 4 is maybe not unique enough and 6 is too long and it can take a lot of tries to get a result and I observed that if the script sends more than 10 search requests in short time, Google temporarily blocks me from further searches.

先决条件是你已经安装了googleryoutube-dl. 我最初的想法是生成随机的 11 个字符串并将它们附加到 YouTube 视频的基本 URL。但是,可能的排列数量是巨大的(26 个大写字母 + 26 个小写字母 + 10 个数字 + 连字符 + 下划线 = 64 个字符;64^11=7.38x10^19 个排列)并且如果地球上每个人都上传就会用完100 亿个视频。这就是为什么随机生成完整的 11 个字符的标识符不是一种可行的方法。我的脚本生成随机的 5 个字符的字符串(变量“rand”)并将它们作为搜索查询传递给 googler。Googler 在 YouTube 网站上搜索这些随机字符串,并且在大多数情况下会返回结果(变量“searchresult”)。如果没有结果,则使用另一个随机字符串重复搜索,依此类推,直到成功。通常需要一到三次尝试。我尝试了不同长度的搜索字符串 - 4 可能不够独特,6 太长,可能需要多次尝试才能获得结果,我观察到如果脚本在短时间内发送了 10 个以上的搜索请求,谷歌暂时阻止我进一步搜索。

In the next step, the script extracts the hyperlinks to the YouTube videos from the search results and puts them in the variable "urls". Then one of them is randomly selected to be played (variable "url") and passed to the player - omxplayer in my case, but you can replace it with whichever player you want. Omxplayer is nice on the Raspberry Pi because it uses the hardware acceleration and outputs via hdmi directly to my TV set. If I change "-o hdmi" to "-o local" the audio is sent via the 3.5 mm stereo Hyman to an external amplifier. Pressing "q" during play stops playing the current video and the next random one starts automatically. It will go on forever till you press Ctrl-C to stop the script.

在下一步中,脚本从搜索结果中提取指向 YouTube 视频的超链接,并将它们放入变量“urls”中。然后随机选择其中一个进行播放(变量“url”)并传递给播放器 - 在我的情况下为 omxplayer,但您可以将其替换为您想要的任何播放器。Omxplayer 在 Raspberry Pi 上很好,因为它使用硬件加速并通过 hdmi 直接输出到我的电视机。如果我将“-o hdmi”更改为“-o local”,音频将通过 3.5 毫米立体声插孔发送到外部放大器。在播放过程中按“q”停止播放当前视频并自动开始下一个随机视频。它会一直持续下去,直到您按 Ctrl-C 停止脚本。

Additional tips

其他提示

With some modifications you can get random videos on a given topic. For example, if we put "Deep Purple" as an additional search term we'll get random music videos by Deep Purple:

通过一些修改,您可以获得关于给定主题的随机视频。例如,如果我们将“Deep Purple”作为附加搜索词,我们将随机获得 Deep Purple 的音乐视频:

    #!/bin/sh
    while [ true ];
    do
    searchresult=""
    while [ -z "$searchresult" ]; do
    rand=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-2};echo)
    echo "$rand"
    searchresult=$(googler -C -n 10 --np -x -w https://www.youtube.com "$rand" "Deep Purple")
    done
    urls=$(echo "$searchresult" | grep -o "https://www.youtube.com/watch?v=...........")
    url=$(shuf -e -n 1 $urls)
    echo "$url"
    omxplayer -o hdmi $(youtube-dl -f mp4 -g "$url")
    done

Note that in the last example I have reduced the randomness factor to a 2-character string because it will be difficult to find a match for a 5-character string in the relatively small subset of all YouTube videos that contain the search term "Deep Purple". Also here I have limited the number of returned search results by googler to 10 to keep them relevant. With 100 I would also get less relevant results like videos of amateurs trying to play songs by Deep Purple.

请注意,在最后一个示例中,我将随机因子减少到 2 个字符的字符串,因为在包含搜索词“Deep Purple ”。同样在这里,我将 googler 返回的搜索结果数量限制为 10,以保持它们的相关性。使用 100 我也会得到不太相关的结果,比如业余爱好者尝试播放 Deep Purple 歌曲的视频。

The next script will play randomly only new videos that have been uploaded within the last 12 hours:

下一个脚本将随机播放过去 12 小时内上传的新视频

    #!/bin/sh
    while [ true ];
    do
    searchresult=$(googler -C -n 100 --np -t h12 -x -w https://www.youtube.com "")
    urls=$(echo "$searchresult" | grep -o "https://www.youtube.com/watch?v=...........")
    url=$(shuf -e -n 1 $urls)
    echo "$url"
    omxplayer -o hdmi $(youtube-dl -f mp4 -g "$url")
    done

You can set different time constraints. See the documentation of googler for more details.

您可以设置不同的时间限制。有关更多详细信息,请参阅 googler 的文档。

回答by madprops

Get a list of words, with hundreds or thousands of words. Then randomly select 2 words from it and use it as a query. This can also be useful if you want to have certain control of how random it could be. For instance you can have a list of english words, or a list of german words. Or have a smaller curated list with words only relevant to a topic you're interested in.

获取包含数百或数千个单词的单词列表。然后从中随机选择2个单词并将其用作查询。如果您想对随机性有一定的控制,这也很有用。例如,您可以有一个英语单词列表或德语单词列表。或者有一个较小的精选列表,其中包含仅与您感兴趣的主题相关的单词。

回答by Vik

At this moment you can get random YouTube video by this URL:

此时你可以通过这个 URL 获得随机的 YouTube 视频:

https://www.googleapis.com/youtube/v3/search?part=snippet

https://www.googleapis.com/youtube/v3/search?part=snippet

And using multiple parameters. You can find it here. But there is a limit: 10 000 requests per day.

并使用多个参数。你可以在这里找到它。但是有一个限制:每天 10 000 个请求。

You can check how it works in this Random YouTube Videosite.

您可以在这个Random YouTube Video网站查看它的工作原理。