I am having trouble getting my video to play even though I am fetching the correct videoID. Am I supposed to use the YouTube feature or should I use something else? Here is my code:
function fetchTrailer() {
// Get the movie title from iniMovieTitle
let movieTitle = iniMovieTitle.value
// Set up the YouTube API request URL, using user input for the movie title
let apiKey = "AIzaSyBQVoRl6mpmh89zNs10LNOu-8tUfs1HqGs" // My YouTube API key
let url = `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${encodeURIComponent(movieTitle)} Trailer&maxResults=1&key=${apiKey}&order=viewCount&type=video`
// Make the API request
fetch(url)
.then(response => response.json()) // Parse the JSON response
.then(data => {
// Check if there are results
if (data.items && data.items.length > 0) {
// Get the video ID from the response
let videoId = data.items[0].id.videoId
console.log("Fetched video ID:", videoId)
// Set the src property of vdPlayer to the YouTube embed URL
ytPlayer.videoID = videoId
} else {
console.log("No trailers found for this movie.")
}
})
.catch(error => console.error("Error fetching video ID:", error))
}
// Trigger the trailer search on button click
btnSearchTrailer.onclick = function() {
fetchTrailer() // Call the fetchTrailer function
}