1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

YouTube APIで作る!HTML・JavaScriptを使ったジュークボックスの実装ガイド

Posted at

はじめに

この記事では、YouTube APIを使ってYouTubeジュークボックスをHTMLとJavaScriptで作成する方法を解説します。YouTube APIを利用して動画を検索し、指定した動画を再生できるシンプルなWebアプリケーションを作成します。

前提条件

  • 基本的なHTML、CSS、JavaScriptの知識がある
  • YouTube APIキーを取得済み(取得方法は後述)

完成画面

スクリーンショット 2024-09-18 18.07.09.png

YouTube APIキーの取得方法

YouTube APIを利用するには、まずAPIキーを取得する必要があります。以下の手順でAPIキーを取得しましょう。

  1. Google Cloud Consoleにアクセスし、Googleアカウントでログインします。
  2. 「プロジェクトを作成」をクリックし、新しいプロジェクトを作成します。
  3. 左側のメニューから「APIとサービス」→「ライブラリ」に移動し、「YouTube Data API v3」を検索して有効化します。
  4. 「認証情報」→「認証情報を作成」→「APIキー」をクリックしてAPIキーを取得します。

取得したAPIキーは後で使用しますので、メモしておいてください。

ファイル構成

今回作成するWebアプリは、以下の3つのファイルで構成されます。

/project-directory
    ├── index.html      (HTMLファイル)
    ├── styles.css      (CSSファイル)
    └── scripts.js      (JavaScriptファイル)

1. HTMLファイルの作成 (index.html)

まず、HTMLファイルを作成します。ここでは、検索ボックス、動画結果表示エリア、YouTubeプレーヤーを配置しています。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YouTube Jukebox</title>
    <link rel="stylesheet" href="styles.css"> <!-- 外部CSSをリンク -->
</head>
<body>

<header>
    <h1>YouTube Jukebox</h1>
</header>

<div id="container">
    <div id="searchBox">
        <input type="text" id="searchQuery" placeholder="動画を検索" />
        <button onclick="searchYouTube()">検索</button>
    </div>

    <div id="results"></div>

    <div id="videoPlayer">
        <iframe id="player" width="560" height="315" src="" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
    </div>
</div>

<script src="scripts.js"></script> <!-- 外部JavaScriptをリンク -->
</body>
</html>

2. CSSファイルの作成 (styles.css)

次に、見た目を整えるためにCSSファイルを作成します。ここでは、レイアウトやボタンのデザインを指定しています。

body {
    font-family: 'Arial', sans-serif;
    background-color: #f0f0f0;
    margin: 0;
    padding: 0;
}

header {
    background-color: #ff0000;
    color: white;
    text-align: center;
    padding: 20px;
}

h1 {
    margin: 0;
    font-size: 2em;
}

#container {
    max-width: 800px;
    margin: 30px auto;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

#searchBox {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
}

#searchQuery {
    width: 70%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 16px;
}

button {
    padding: 10px 20px;
    background-color: #ff0000;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
    font-size: 16px;
}

button:hover {
    background-color: #cc0000;
}

#results {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    justify-content: center;
}

.videoItem {
    width: 180px;
    background-color: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    text-align: center;
}

.videoItem img {
    width: 100%;
    border-bottom: 1px solid #ddd;
}

.videoItem p {
    font-size: 14px;
    padding: 10px;
    margin: 0;
}

.videoItem button {
    background-color: #ff0000;
    color: white;
    border: none;
    border-radius: 0 0 8px 8px;
    padding: 10px;
    width: 100%;
    cursor: pointer;
}

.videoItem button:hover {
    background-color: #cc0000;
}

#videoPlayer {
    margin-top: 20px;
    text-align: center;
}

3. JavaScriptファイルの作成 (scripts.js)

最後に、YouTube APIを使用して動画検索と再生を行うためのJavaScriptファイルを作成します。ここで取得したAPIキーを使用します。

const apiKey = 'YOUR_YOUTUBE_API_KEY'; // ここにYouTube APIキーを挿入
const player = document.getElementById('player');

function searchYouTube() {
    const query = document.getElementById('searchQuery').value;
    const url = `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(query)}&type=video&key=${apiKey}`;

    fetch(url)
        .then(response => response.json())
        .then(data => {
            displayResults(data.items.slice(0, 4)); // 最初の4件に限定
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

function displayResults(videos) {
    const resultsDiv = document.getElementById('results');
    resultsDiv.innerHTML = '';

    videos.forEach(video => {
        const videoId = video.id.videoId;
        const title = video.snippet.title;
        const thumbnail = video.snippet.thumbnails.default.url;

        const videoElement = document.createElement('div');
        videoElement.classList.add('videoItem');
        videoElement.innerHTML = `
            <img src="${thumbnail}" alt="${title}">
            <p>${title}</p>
            <button onclick="playVideo('${videoId}')">再生</button>
        `;

        resultsDiv.appendChild(videoElement);
    });
}

function playVideo(videoId) {
    player.src = `https://www.youtube.com/embed/${videoId}?autoplay=1`;
}

おわりに

これで、YouTube APIを使用してシンプルなジュークボックスが作成できました。このWebアプリケーションを拡張して、再生リストや検索条件のカスタマイズなど、さまざまな機能を追加することも可能です。

この記事が参考になれば幸いです。興味があれば、ぜひ試してみてください!

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?