-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
170 lines (147 loc) · 5.93 KB
/
main.js
File metadata and controls
170 lines (147 loc) · 5.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
document.addEventListener('DOMContentLoaded', () => {
// --- CONFIGURATION ---
const YOUTUBE_API_KEY = 'YOUR_YOUTUBE_API_KEY'; // User needs to replace this
// ---------------------
// Global state
const playlist = {
story: '',
songs: [] // {id, title, image}
};
let player; // YouTube player instance
let currentTrack = 0;
// DOM Elements
const searchBtn = document.getElementById('search-btn');
const searchInput = document.getElementById('search');
const searchResultsContainer = document.getElementById('search-results');
const storyInput = document.getElementById('story');
const playlistElement = document.getElementById('playlist');
const playAllBtn = document.getElementById('play-btn');
const imageDisplay = document.getElementById('current-song-image');
const storyDisplay = document.getElementById('story-display');
// --- 1. Search & Add to Playlist ---
// Live YouTube search
searchBtn.addEventListener('click', async () => {
const query = searchInput.value.trim();
if (!query) return;
if (YOUTUBE_API_KEY === 'YOUR_YOUTUBE_API_KEY') {
alert('Please provide a valid YouTube API key in main.js');
return;
}
const endpoint = `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(query)}&type=video&key=${YOUTUBE_API_KEY}`;
try {
const response = await fetch(endpoint);
const data = await response.json();
displaySearchResults(data.items || []);
} catch (error) {
console.error('Error fetching from YouTube API:', error);
searchResultsContainer.innerHTML = '<p>Error fetching results.</p>';
}
});
function displaySearchResults(results) {
searchResultsContainer.innerHTML = '';
const resultList = document.createElement('ul');
results.forEach(result => {
const li = document.createElement('li');
li.innerHTML = `
<img src="${result.snippet.thumbnails.default.url}" alt="Thumbnail" width="80">
<span>${result.snippet.title}</span>
<button class="add-btn" data-id="${result.id.videoId}" data-title="${result.snippet.title}">Add</button>
`;
resultList.appendChild(li);
});
searchResultsContainer.appendChild(resultList);
}
// Add to playlist (with image prompt)
searchResultsContainer.addEventListener('click', (e) => {
if (e.target.classList.contains('add-btn')) {
const imageUrl = prompt('Enter an image URL for this song:');
if (imageUrl) {
const song = {
id: e.target.dataset.id,
title: e.target.dataset.title,
image: imageUrl
};
playlist.songs.push(song);
renderPlaylist();
}
}
});
// Render the playlist in the editor
function renderPlaylist() {
playlistElement.innerHTML = '';
if (playlist.songs.length === 0) {
playlistElement.innerHTML = '<li>Your playlist is empty.</li>';
} else {
playlist.songs.forEach((song, index) => {
const li = document.createElement('li');
li.textContent = song.title;
li.dataset.index = index;
playlistElement.appendChild(li);
});
}
}
// --- 2. YouTube IFrame Player Setup ---
// Load the IFrame Player API code asynchronously.
const tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// This function creates an <iframe> (and YouTube player) after the API code downloads.
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
height: '113',
width: '200',
playerVars: { 'autoplay': 0, 'controls': 1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) {
// Player is ready
}
// The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
playNextSong();
}
}
function playNextSong() {
currentTrack++;
if (currentTrack < playlist.songs.length) {
player.loadVideoById(playlist.songs[currentTrack].id);
updatePlayerView(currentTrack);
} else {
// End of playlist
imageDisplay.style.backgroundImage = '';
imageDisplay.querySelector('.placeholder-text').style.display = 'block';
}
}
function updatePlayerView(trackIndex) {
const song = playlist.songs[trackIndex];
imageDisplay.style.backgroundImage = `url(${song.image})`;
imageDisplay.querySelector('.placeholder-text').style.display = 'none';
}
// --- 3. Play All Button Logic ---
playAllBtn.addEventListener('click', () => {
if (playlist.songs.length === 0) {
alert('Please add at least one song to your playlist.');
return;
}
// Update story
playlist.story = storyInput.value;
storyDisplay.textContent = playlist.story;
// Start playback
currentTrack = 0;
updatePlayerView(currentTrack);
if (player && typeof player.loadVideoById === 'function') {
player.loadVideoById(playlist.songs[currentTrack].id);
} else {
alert("Player is not ready yet. Please wait a moment.");
}
});
// Initial render
renderPlaylist();
});