xxxxxxxxxx
78
var videoData; // To store the JSON file content
var input; // For duration input
var targetSeconds; // Target duration in seconds
function setup() {
createCanvas(400, 300);
// Input for duration (in format MM:SS)
input = createInput();
input.position(10, 10);
input.attribute('placeholder', 'Enter duration (MM:SS)');
// Create a button to fetch video
var button = createButton('Search Funny Cats');
button.position(input.x + input.width + 10, 10);
button.mousePressed(fetchVideos);
// Instructions on canvas
textSize(12);
fill(255);
text("Search for 'Funny Cats' videos by length:", 10, 50);
// Load the JSON file
loadJSON('videos_by_duration.json', (data) => {
videoData = data;
console.log('JSON data loaded:', videoData);
});
}
// Convert duration MM:SS to seconds
function durationToSeconds(duration) {
let parts = duration.split(':').map(Number);
return parts.length === 2 ? parts[0] * 60 + parts[1] : 0;
}
// Fetch videos from the JSON file
function fetchVideos() {
// Parse the desired duration from the input
let durationInput = input.value();
targetSeconds = durationToSeconds(durationInput);
if (isNaN(targetSeconds) || targetSeconds <= 0) {
console.error('Invalid duration format. Use MM:SS.');
return;
}
if (!videoData) {
console.error('Video data not loaded yet.');
return;
}
// Check if there are any videos for the given duration
let videos = videoData[targetSeconds] || [];
if (videos.length === 0) {
console.log('No videos found for this duration.');
return;
}
// Display the first video that matches the duration
let video = videos[0]; // You can add logic to randomly pick a video if multiple are available
displayVideo(video.title, video.id);
}
// Display the video details and embed it
function displayVideo(title, videoId) {
background(0);
textSize(16);
fill(255);
text('Title: ' + title, 10, 80);
// Embed the video
let 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 iframe creation
}