首页 > 解决方案 > 如何使用 YouTube Data API v3 获取直播小 URL

问题描述

function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("YOUR_API_KEY");
    return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.youtube.liveStreams.list({
      "part": [
        "snippet,cdn,contentDetails,status"
        //"cdn"
      ],
      "mine": true
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
                
                var responseData = JSON.stringify(response);
                alert(responseData);
                
                //alert(response.result.items);
                
                var itemsArr = response.result.items;
                var itemObj = itemsArr[0];
                alert('streamName = ' + itemObj.cdn.ingestionInfo.streamName);
                
                //alert(responseData.result);
                //var result = responseData.result;
                
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
  });
<script src="https://apis.google.com/js/api.js"></script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

我是 YouTube 直播的新手。我正在通过我的应用程序做到这一点。我在这个门户网站上浏览了各种问题/答案,但找不到/理解获得它的方法。

有什么方法(使用 YouTube Data API v3)来获取直播小 URL(类似https://youtu.be/OHi8m4o8XeQ),以便我可以将我的直播分享给我的观众?

-从 YouTube Data API v3 获得了一个流密钥/名称(20 个字符的字母数字密钥,中间有四个),我将使用它来流式传输到 YouTube。

我正在添加一个屏幕截图以供参考。我想要右上角的小网址(类似于https://youtu.be/someid )。

请在这里找到图片

标签: youtube-apiyoutube-data-apiyoutube-livestreaming-apitinyurl

解决方案


YouTube 与给定视频相关联的缩短 URL(由其 ID 标识VIDEO_ID)具有以下形式:

https://youtu.be/VIDEO_ID,

where(通常,虽然没有正式记录)VIDEO_ID遵循以下正则表达式模式:

^[0-9a-zA-Z_-]{11}$.

在直播的情况下,为了能够共享您创建的一个此类流的缩短 URL,您应该获取与该流关联的视频 ID

该视频 ID 将作为绑定到您的直播流idLiveBroadcasts资源的属性值找到。


推荐阅读