xxxxxxxxxx
59
var videoData; // To store the API response
var api = 'https://www.googleapis.com/youtube/v3/search?'; // Use search endpoint
var apiKey = 'AIzaSyDb5lnof_d87ZJgh9XauyNIM82nBHpnau4'; // Replace with your valid API key
var input;
function setup() {
createCanvas(400, 200);
// Create an input box for the search query
input = createInput();
input.position(10, 10);
// Create a button to fetch video details
var button = createButton('Search Video');
button.position(input.x + input.width + 10, 10);
button.mousePressed(fetchVideo);
// Instructions on canvas
textSize(12);
fill(255);
text("Enter a search term to fetch and display a video:", 10, 50);
}
function fetchVideo() {
// Construct the API URL
var searchQuery = input.value();
var url = `${api}key=${apiKey}&q=${searchQuery}&type=video&part=snippet&maxResults=1`;
// Fetch video data from YouTube API
loadJSON(url, gotData);
}
function gotData(data) {
// Store the fetched video data
videoData = data;
}
function draw() {
background(0);
if (videoData && videoData.items && videoData.items.length > 0) {
// Display video details
var snippet = videoData.items[0].snippet;
fill(255);
textSize(16);
text('Title: ' + snippet.title, 10, 80);
textSize(12);
text('Description: ' + snippet.description, 10, 100, width - 20);
// Embed the video
var videoId = videoData.items[0].id.videoId;
var iframe = createElement('iframe');
iframe.attribute('src', 'https://www.youtube.com/embed/' + videoId);
iframe.attribute('width', '400');
iframe.attribute('height', '200');
iframe.position(10, 150);
noLoop(); // Prevent repeated creation of iframes
}
}