|
let player; |
|
let currentPlaylist = []; |
|
let currentTrackIndex = 0; |
|
|
|
function onYouTubeIframeAPIReady() { |
|
player = new YT.Player('player', { |
|
height: '0', |
|
width: '0', |
|
playerVars: { |
|
'playsinline': 1, |
|
'controls': 0 |
|
}, |
|
events: { |
|
'onStateChange': onPlayerStateChange |
|
} |
|
}); |
|
} |
|
|
|
function onPlayerStateChange(event) { |
|
if (event.data === YT.PlayerState.ENDED) { |
|
nextTrack(); |
|
} |
|
updatePlayPauseButton(); |
|
} |
|
|
|
function updatePlayPauseButton() { |
|
const btn = document.getElementById('playPauseBtn'); |
|
if (player && player.getPlayerState() === YT.PlayerState.PLAYING) { |
|
btn.textContent = 'Pause'; |
|
} else { |
|
btn.textContent = 'Play'; |
|
} |
|
} |
|
|
|
function search() { |
|
const query = document.getElementById('searchInput').value; |
|
fetch('/search', { |
|
method: 'POST', |
|
headers: { |
|
'Content-Type': 'application/json', |
|
}, |
|
body: JSON.stringify({ query: query }) |
|
}) |
|
.then(response => response.json()) |
|
.then(data => { |
|
displaySearchResults(data); |
|
}) |
|
.catch(error => console.error('Error:', error)); |
|
} |
|
|
|
function displaySearchResults(results) { |
|
const container = document.getElementById('searchResults'); |
|
container.innerHTML = ''; |
|
|
|
results.forEach((song, index) => { |
|
const div = document.createElement('div'); |
|
div.className = 'song-item'; |
|
div.innerHTML = ` |
|
<strong>${song.title}</strong> - ${song.artists[0].name} |
|
`; |
|
div.onclick = () => playSong(song, index, results); |
|
container.appendChild(div); |
|
}); |
|
} |
|
|
|
function playSong(song, index, playlist) { |
|
currentPlaylist = playlist; |
|
currentTrackIndex = index; |
|
|
|
const videoId = song.videoId; |
|
document.getElementById('currentSongTitle').textContent = `${song.title} - ${song.artists[0].name}`; |
|
document.getElementById('player-container').classList.remove('d-none'); |
|
|
|
player.loadVideoById(videoId); |
|
player.playVideo(); |
|
} |
|
|
|
function togglePlayPause() { |
|
if (player) { |
|
if (player.getPlayerState() === YT.PlayerState.PLAYING) { |
|
player.pauseVideo(); |
|
} else { |
|
player.playVideo(); |
|
} |
|
} |
|
} |
|
|
|
function nextTrack() { |
|
if (currentPlaylist.length > 0) { |
|
currentTrackIndex = (currentTrackIndex + 1) % currentPlaylist.length; |
|
playSong(currentPlaylist[currentTrackIndex], currentTrackIndex, currentPlaylist); |
|
} |
|
} |
|
|
|
function previousTrack() { |
|
if (currentPlaylist.length > 0) { |
|
currentTrackIndex = (currentTrackIndex - 1 + currentPlaylist.length) % currentPlaylist.length; |
|
playSong(currentPlaylist[currentTrackIndex], currentTrackIndex, currentPlaylist); |
|
} |
|
} |
|
|