【问题标题】:How to write a JavaScript download function in my YouTube MP4 & MP3 Downloader如何在我的 YouTube MP4 和 MP3 下载器中编写 JavaScript 下载函数
【发布时间】:2022-05-10 05:25:12
【问题描述】:

// put your own value below!
const apiKey = "AIzaSyCGKrLxvpot6hrekFHQTPaCGeOFj92T3ao";
const searchURL = "https://www.googleapis.com/youtube/v3/search";

function formatQueryParams(params) {
  const queryItems = Object.keys(params).map(
    key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
  );
  return queryItems.join("&");
}

function displayResults(responseJson) {
  // if there are previous results, remove them
  console.log(responseJson);
  $("#results-list").empty();
  // iterate through the items array
  for (let i = 0; i < responseJson.items.length; i++) {
    // for each video object in the items
    //array, add a list item to the results
    //list with the video title, description,
    //and thumbnail
    $("#results-list").append(
      `<li><h3>${responseJson.items[i].snippet.title}</h3>
      <p>${responseJson.items[i].snippet.description}</p>
      <img src='${responseJson.items[i].snippet.thumbnails.default.url}'>
      </li>`
    );
  }
  //display the results section
  $("#results").removeClass("hidden");
}

async function downloadVideo(videoId) {
  console.log(videoId);
  const response = await fetch(`https://getvideo.p.rapidapi.com/?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D${videoId}`, {
    headers: {
      "X-RapidAPI-Host": "getvideo.p.rapidapi.com",
      "X-RapidAPI-Key": "d390d7b0e9msh42dc09f4e07e285p1486c4jsne0a4edb9e61e"
    }
  });
  const data = await response.json();
  return {
    audio: data.streams.filter(stream => {
      return stream.format === "audio only";
    })[0].url,
    video: data.streams.filter(stream => {
      return stream.format !== "audio only";
    })[0].url
  };
}

function getYouTubeVideos(query, maxResults = 50) {
  const params = {
    key: apiKey,
    q: query,
    part: "snippet",
    maxResults,
    type: "video"
  };
  const queryString = formatQueryParams(params);
  const url = searchURL + "?" + queryString;

  console.log(url);

  fetch(url)
    .then(response => {
      if (response.ok) {
        return response.json();
      }
      throw new Error(response.statusText);
    })
    .then(responseJson => downloadVideo(responseJson.items[0].id.videoId))
    .then(download => console.log(download))
    // .then(responseJson => displayResults(responseJson))
    .catch(err => {
      $("#js-error-message").text(`Something went wrong: ${err.message}`);
    });
}

function watchForm() {
  $("form").submit(event => {
    event.preventDefault();
    const searchTerm = $("#js-search-term").val();
    const maxResults = $("#js-max-results").val();
    getYouTubeVideos(searchTerm, maxResults);
  });
}

$(watchForm);
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>YouTube video finder</title>
    <link rel="stylesheet" href="style\style.css" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
    />
    <script
      src="https://code.jquery.com/jquery-3.3.1.js"
      integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
      crossorigin="anonymous"
    ></script>
  </head>

  <body>
    <div class="container">
      <div class="left">
        <h1 class="finder-heading">Download a YouTube video</h1>
        <form id="js-form">
          <label for="search-term"></label>
          <input
            class="search-input"
            type="text"
            name="search-term"
            id="js-search-term"
            required
            placeholder="Search YouTube Videos..."
          />

          <label for="max-results"></label>
          <input
            class="max-number"
            type="number"
            name="max-results"
            id="js-max-results"
            value="10"
          />

          <input class="go-button" type="submit" value="Search" />
        </form>
      </div>

      <!-- <div class="right">
        <h1 class="downloader-heading">Download a YouTube video</h1>
        <input class="URL-input" placeholder="Paste YouTube link here..." />
        <button class="download-button">
          <i class="fa fa-download"></i> Download
        </button>
      </div> -->

      <p id="js-error-message" class="error-message"></p>
      <section id="results" class="hidden">
        <h2>Search results</h2>
        <ul id="results-list"></ul>
      </section>
    </div>
    <script src="apps\app.js"></script>
  </body>
</html>

我正在制作一个使用 youtube API 和 GET Video and Audio URL API 的 2 API 混搭的网络应用程序。我遇到的问题是我不知道如何编写该项目下载部分所需的 javascript...

目前我已经将 javascript 编码到一个点,如果您运行它并在 google chrome 中检查,您将在控制台中看到它如何捕获您选择插入的任何视频链接的音频文件和视频文件到输入。

我希望这能够捕获视频并在 HTML 中生成一个缩略图,并提供下载 MP4 或 MP3 的给定选项

【问题讨论】:

    标签: javascript jquery html api


    【解决方案1】:

    问题是您的.then() 的顺序。您在每次调用时都返回数据,并且在一次调用中返回一个 console.log(),这将是未定义的。你可以这样修复它:

    function getYouTubeVideos(query, maxResults = 50) {
      const params = {
        key: apiKey,
        q: query,
        part: "snippet",
        maxResults,
        type: "video"
      };
      const queryString = formatQueryParams(params);
      const url = searchURL + "?" + queryString;
    
      console.log(url);
    
      fetch(url)
              .then(r => r.json())
              .then(data => {
                displayResults(data);
                return downloadVideo(data.items[0].id.videoId);
              })
              .then(download => console.log(download))
              .catch(err => {
                $("#js-error-message").text(`Something went wrong: ${err.message}`);
              });
    }
    

    【讨论】:

      【解决方案2】:

      我使用我的 API 密钥及其工作

      const apiKey = "Your Key";
      const searchURL = "https://www.googleapis.com/youtube/v3/search";
      
      function formatQueryParams(params) {
        const queryItems = Object.keys(params).map(
          key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
        );
        return queryItems.join("&");
      }
      
      function displayResults(responseJson) {
        console.log(responseJson);
        $("#results-list").empty();
       
        for (let i = 0; i < responseJson.items.length; i++) {
        
          $("#results-list").append(
            `<li><h3>${responseJson.items[i].snippet.title}</h3>
            <p>${responseJson.items[i].snippet.description}</p>
            <img src='${responseJson.items[i].snippet.thumbnails.default.url}'>
            </li>`
          );
        }
        
        $("#results").removeClass("hidden");
      }
      
      async function downloadVideo(videoId) {
        console.log(videoId);
        const response = await fetch(`https://getvideo.p.rapidapi.com/?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D${videoId}`, {
          headers: {
            "X-RapidAPI-Host": "getvideo.p.rapidapi.com",
            "X-RapidAPI-Key": "d390d7b0e9msh42dc09f4e07e285p1486c4jsne0a4edb9e61e"
          }
        });
        const data = await response.json();
        return {
          audio: data.streams.filter(stream => {
            return stream.format === "audio only";
          })[0].url,
          video: data.streams.filter(stream => {
            return stream.format !== "audio only";
          })[0].url
        };
      }
      
      function getYouTubeVideos(query, maxResults = 50) {
        const params = {
          key: apiKey,
          q: query,
          part: "snippet",
          maxResults,
          type: "video"
        };
        const queryString = formatQueryParams(params);
        const url = searchURL + "?" + queryString;
      
        console.log(url);
      
         fetch(url)
            .then(r => r.json())
            .then(data => {
              displayResults(data);
              return downloadVideo(data.items[0].id.videoId);
            })
            .then(download => console.log(download))
            .catch(err => {
              $("#js-error-message").text(`Something went wrong: ${err.message}`);
            });
      }
      
      
      function watchForm() {
        $("form").submit(event => {
          event.preventDefault();
          const searchTerm = $("#js-search-term").val();
          const maxResults = $("#js-max-results").val();
          getYouTubeVideos(searchTerm, maxResults);
        });
      }
      
      $(watchForm);
      <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <meta http-equiv="X-UA-Compatible" content="ie=edge" />
          <title>YouTube video finder</title>
          <link rel="stylesheet" href="style\style.css" />
          <link
            rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
          />
          <script
            src="https://code.jquery.com/jquery-3.3.1.js"
            integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
            crossorigin="anonymous"
          ></script>
        </head>
      
        <body>
          <div class="container">
            <div class="left">
              <h1 class="finder-heading">Download a YouTube video</h1>
              <form id="js-form">
                <label for="search-term"></label>
                <input
                  class="search-input"
                  type="text"
                  name="search-term"
                  id="js-search-term"
                  required
                  placeholder="Search YouTube Videos..."
                />
      
                <label for="max-results"></label>
                <input
                  class="max-number"
                  type="number"
                  name="max-results"
                  id="js-max-results"
                  value="10"
                />
      
                <input class="go-button" type="submit" value="Search" />
              </form>
            </div>
      
            <!-- <div class="right">
              <h1 class="downloader-heading">Download a YouTube video</h1>
              <input class="URL-input" placeholder="Paste YouTube link here..." />
              <button class="download-button">
                <i class="fa fa-download"></i> Download
              </button>
            </div> -->
      
            <p id="js-error-message" class="error-message"></p>
            <section id="results" class="hidden">
              <h2>Search results</h2>
              <ul id="results-list"></ul>
            </section>
          </div>
          <script src="apps\app.js"></script>
        </body>
      </html>

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2012-02-09
      • 2012-02-25
      • 1970-01-01
      • 2014-02-18
      • 2023-04-09
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2020-08-03
      相关资源
      最近更新 更多