To enable your video player to handle any video file extension, you'll need to make the following modifications to your existing script:
-
Remove the Fixed <source> Element:
The current <source> element is hardcoded to video/mp4, which restricts the player to only MP4 files. By removing this element and setting the video source (src) directly, the browser can automatically handle various video formats based on the file's MIME type.
-
Dynamically Set the Video Source and Type:
When a user selects a video file, retrieve its MIME type and set both the src and type attributes dynamically. This ensures that the player correctly identifies and plays the video regardless of its format.
-
Update Playlist Video Handling:
Ensure that videos added to playlists also correctly set their MIME types when played.
Below is the modified code with detailed explanations:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Stylish Video Player with Playlists</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* Custom styles for the resizable playlist panel */
.resizer {
width: 5px;
cursor: ew-resize;
background-color: transparent;
position: relative;
z-index: 10;
}
.resizer:hover {
background-color: #ddd;
}
/* Prevent text selection while resizing */
.no-select {
user-select: none;
}
</style>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
<div class="bg-white shadow-lg rounded-lg flex flex-col md:flex-row h-full w-full max-w-6xl">
<div class="flex flex-col md:flex-row flex-1 overflow-hidden">
<!-- Video Player Section -->
<div class="flex-shrink-0 p-4 flex flex-col items-center justify-center">
<video id="videoPlayer" class="w-full md:w-[800px] h-auto md:h-[600px] rounded" controls>
Your browser does not support the video tag.
</video>
<div class="mt-4 flex flex-col md:flex-row space-y-2 md:space-y-0 md:space-x-2 w-full md:w-auto">
<!-- Add Video to Site Button -->
<div class="flex-1">
<input type="file" id="addVideoBtn" accept="video/*" class="hidden">
<label for="addVideoBtn" class="cursor-pointer block text-center px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
Add Video to Site
</label>
</div>
<!-- Watch Playlist Button -->
<div class="flex-1">
<button id="watchPlaylistBtn" class="w-full md:w-auto px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 disabled:opacity-50" disabled>
Watch Playlist
</button>
</div>
</div>
</div>
<!-- Resizer Handle (Hidden on small screens) -->
<div id="resizer" class="resizer hidden md:block"></div>
<!-- Playlist Panel -->
<div id="playlistPanel" class="bg-gray-50 p-4 border-l overflow-y-auto w-full md:w-1/4">
<h2 class="text-xl font-semibold mb-4">Playlists</h2>
<div id="playlists" class="mb-4">
<!-- Dynamic Playlists Will Appear Here -->
</div>
<div class="mt-4">
<input type="text" id="newPlaylistName" placeholder="New Playlist Name" class="w-full p-2 border rounded mb-2">
<button id="createPlaylistBtn" class="w-full px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600">
Create Playlist
</button>
</div>
</div>
</div>
</div>
<!-- JavaScript for Functionality -->
<script>
// Utility Function to Sanitize IDs
function sanitizeId(name) {
return name.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase();
}
// Elements
const videoPlayer = document.getElementById('videoPlayer');
const addVideoBtn = document.getElementById('addVideoBtn');
const watchPlaylistBtn = document.getElementById('watchPlaylistBtn');
const playlistsContainer = document.getElementById('playlists');
const createPlaylistBtn = document.getElementById('createPlaylistBtn');
const newPlaylistNameInput = document.getElementById('newPlaylistName');
const resizer = document.getElementById('resizer');
const playlistPanel = document.getElementById('playlistPanel');
// Data Structure for Playlists
const playlists = {};
// Currently Selected Playlist for Watching
let selectedPlaylist = null;
let autoplayQueue = [];
let currentAutoplayIndex = 0;
// Function to Set Video Source and Type
function setVideoSource(url, type) {
videoPlayer.src = url;
videoPlayer.type = type;
videoPlayer.load(); // Reload the video with the new source
videoPlayer.play();
}
// Handle Add Video to Site
addVideoBtn.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
const url = URL.createObjectURL(file);
const type = file.type || '';
setVideoSource(url, type);
}
// Reset the input value to allow re-uploading the same file if needed
addVideoBtn.value = '';
});
// Handle Create Playlist
createPlaylistBtn.addEventListener('click', () => {
const name = newPlaylistNameInput.value.trim();
if (name) {
const sanitizedName = sanitizeId(name);
if (!playlists[sanitizedName]) {
playlists[sanitizedName] = {
originalName: name,
videos: []
};
renderPlaylists();
newPlaylistNameInput.value = '';
} else {
alert('Playlist with this name already exists.');
}
} else {
alert('Please enter a valid playlist name.');
}
});
// Render Playlists
function renderPlaylists() {
playlistsContainer.innerHTML = '';
for (const playlistId in playlists) {
const playlist = playlists[playlistId];
const playlistDiv = document.createElement('div');
playlistDiv.className = 'mb-4 p-2 bg-white rounded shadow hover:bg-blue-50';
// Playlist Header
const header = document.createElement('div');
header.className = 'flex justify-between items-center';
const title = document.createElement('span');
title.textContent = playlist.originalName;
title.className = 'font-medium cursor-pointer text-gray-800 hover:text-blue-600';
title.addEventListener('click', () => selectPlaylist(playlistId));
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.className = 'text-red-500 hover:underline';
deleteBtn.addEventListener('click', () => {
if (confirm(`Are you sure you want to delete the playlist "${playlist.originalName}"?`)) {
delete playlists[playlistId];
if (selectedPlaylist === playlistId) {
selectedPlaylist = null;
watchPlaylistBtn.disabled = true;
}
renderPlaylists();
}
});
header.appendChild(title);
header.appendChild(deleteBtn);
playlistDiv.appendChild(header);
// Playlist Actions
const actions = document.createElement('div');
actions.className = 'mt-2 flex space-x-2';
// Add Video to Playlist
const addVideoInput = document.createElement('input');
addVideoInput.type = 'file';
addVideoInput.accept = 'video/*';
addVideoInput.className = 'hidden';
addVideoInput.id = `addVideo-${playlistId}`;
addVideoInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const url = URL.createObjectURL(file);
const type = file.type || '';
playlist.videos.push({
name: file.name,
url: url,
type: type
});
renderPlaylists();
}
// Reset the input
addVideoInput.value = '';
});
const addVideoLabel = document.createElement('label');
addVideoLabel.htmlFor = `addVideo-${playlistId}`;
addVideoLabel.className = 'cursor-pointer px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm';
addVideoLabel.textContent = 'Add Video';
const addVideoBtnWrapper = document.createElement('div');
addVideoBtnWrapper.appendChild(addVideoInput);
addVideoBtnWrapper.appendChild(addVideoLabel);
// Watch Playlist Button for Individual Playlists
const watchBtn = document.createElement('button');
watchBtn.textContent = 'Watch';
watchBtn.className = 'px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 text-sm';
watchBtn.addEventListener('click', () => watchSelectedPlaylist(playlistId));
actions.appendChild(addVideoBtnWrapper);
actions.appendChild(watchBtn);
playlistDiv.appendChild(actions);
// Videos List
if (playlist.videos.length > 0) {
const videoList = document.createElement('ul');
videoList.className = 'mt-2 pl-4 list-disc';
playlist.videos.forEach((video, index) => {
const li = document.createElement('li');
li.className = 'flex justify-between items-center mb-1 bg-gray-100 p-1 rounded cursor-pointer hover:bg-gray-200';
const videoName = document.createElement('span');
videoName.textContent = video.name;
videoName.className = 'flex-1 text-left'; // Removed 'truncate' class for full name display
videoName.addEventListener('click', () => {
setVideoSource(video.url, video.type);
});
const removeVideoBtn = document.createElement('button');
removeVideoBtn.textContent = 'Remove';
removeVideoBtn.className = 'text-red-400 text-xs hover:underline ml-2';
removeVideoBtn.addEventListener('click', (e) => {
e.stopPropagation();
if (confirm(`Remove "${video.name}" from playlist "${playlist.originalName}"?`)) {
playlist.videos.splice(index, 1);
renderPlaylists();
}
});
li.appendChild(videoName);
li.appendChild(removeVideoBtn);
videoList.appendChild(li);
});
playlistDiv.appendChild(videoList);
}
playlistsContainer.appendChild(playlistDiv);
}
}
// Select Playlist
function selectPlaylist(playlistId) {
selectedPlaylist = playlistId;
// Highlight selected playlist
const allTitles = playlistsContainer.querySelectorAll('span.font-medium');
allTitles.forEach(title => {
if (title.textContent === playlists[playlistId].originalName) {
title.classList.add('text-blue-600');
} else {
title.classList.remove('text-blue-600');
}
});
// Enable Watch Playlist button if the selected playlist has videos
if (playlists[playlistId].videos.length > 0) {
watchPlaylistBtn.disabled = false;
} else {
watchPlaylistBtn.disabled = true;
}
}
// Watch Playlist Button Handler
watchPlaylistBtn.addEventListener('click', () => {
if (selectedPlaylist && playlists[selectedPlaylist].videos.length > 0) {
startAutoplay(selectedPlaylist);
}
});
// Watch Individual Playlist
function watchSelectedPlaylist(playlistId) {
if (playlists[playlistId].videos.length > 0) {
selectedPlaylist = playlistId;
watchPlaylistBtn.disabled = false;
// Highlight the selected playlist
selectPlaylist(playlistId);
startAutoplay(playlistId);
}
}
// Start Autoplay for a Playlist
function startAutoplay(playlistId) {
autoplayQueue = playlists[playlistId].videos.map(video => ({
url: video.url,
type: video.type
}));
currentAutoplayIndex = 0;
playNextAutoplay();
}
// Play Next Video in Autoplay Queue
function playNextAutoplay() {
if (currentAutoplayIndex < autoplayQueue.length) {
const video = autoplayQueue[currentAutoplayIndex];
setVideoSource(video.url, video.type);
currentAutoplayIndex++;
}
}
// Listen for Video End to Autoplay Next
videoPlayer.addEventListener('ended', () => {
if (currentAutoplayIndex < autoplayQueue.length) {
playNextAutoplay();
}
});
// Resizable Playlist Panel Functionality
let isResizing = false;
resizer.addEventListener('mousedown', function(e) {
isResizing = true;
document.body.style.cursor = 'ew-resize';
e.preventDefault(); // Prevent text selection
});
window.addEventListener('mousemove', function(e) {
if (!isResizing) return;
// Calculate new width for the playlist panel
const containerRect = playlistPanel.parentElement.getBoundingClientRect();
let newWidth = e.clientX - containerRect.left;
// Set minimum and maximum width
const minWidth = 200; // Minimum width in pixels
const maxWidth = containerRect.width - 200; // Maximum width to prevent too small video player
if (newWidth < minWidth) newWidth = minWidth;
if (newWidth > maxWidth) newWidth = maxWidth;
// Apply new width
playlistPanel.style.width = `${newWidth}px`;
});
window.addEventListener('mouseup', function(e) {
if (isResizing) {
isResizing = false;
document.body.style.cursor = 'default';
}
});
// Initial Render
renderPlaylists();
</script>
</body>
</html>
Detailed Explanation of Changes
1. Removing the Fixed <source> Element
Original Code:
<video id="videoPlayer" class="w-full md:w-[800px] h-auto md:h-[600px] rounded" controls>
<source src="" type="video/mp4">
Your browser does not support the video tag.
</video>
Modified Code:
<video id="videoPlayer" class="w-full md:w-[800px] h-auto md:h-[600px] rounded" controls>
Your browser does not support the video tag.
</video>
Reason:
By removing the static <source> element, you allow the JavaScript to dynamically set the video source and type based on the user's selected file. This makes the player flexible to handle any video format supported by the browser.
2. Dynamically Setting the Video Source and Type
Original JavaScript for Setting Video Source:
videoPlayer.src = url;
videoPlayer.play();
Modified JavaScript:
// Function to Set Video Source and Type
function setVideoSource(url, type) {
videoPlayer.src = url;
videoPlayer.type = type;
videoPlayer.load(); // Reload the video with the new source
videoPlayer.play();
}
Usage in Event Listeners:
-
Adding a Video to the Site:
addVideoBtn.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
const url = URL.createObjectURL(file);
const type = file.type || '';
setVideoSource(url, type);
}
addVideoBtn.value = '';
});
-
Playing a Video from the Playlist:
videoName.addEventListener('click', () => {
setVideoSource(video.url, video.type);
});
Reason:
The setVideoSource function not only sets the src attribute but also the type attribute based on the file's MIME type. This ensures that the browser correctly identifies the video format, enhancing compatibility with various video extensions.
3. Handling Video Type in Playlists
When adding videos to playlists, store their MIME types alongside their URLs:
addVideoInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const url = URL.createObjectURL(file);
const type = file.type || '';
playlist.videos.push({
name: file.name,
url: url,
type: type
});
renderPlaylists();
}
addVideoInput.value = '';
});
Reason:
Storing the MIME type for each video in the playlist allows you to set the correct type when playing videos from the playlist, ensuring broader format support.
4. Updating the startAutoplay Function
Modified startAutoplay to handle both url and type for each video:
function startAutoplay(playlistId) {
autoplayQueue = playlists[playlistId].videos.map(video => ({
url: video.url,
type: video.type
}));
currentAutoplayIndex = 0;
playNextAutoplay();
}
function playNextAutoplay() {
if (currentAutoplayIndex < autoplayQueue.length) {
const video = autoplayQueue[currentAutoplayIndex];
setVideoSource(video.url, video.type);
currentAutoplayIndex++;
}
}
Reason:
Ensuring that each video in the autoplay queue has both url and type allows seamless playback of various video formats without manual intervention.
5. Ensuring Compatibility and Robustness
-
Fallback for MIME Type:
const type = file.type || '';
If the MIME type isn't available, an empty string is used. Most browsers can infer the type from the file's extension even if the type attribute is empty.
-
Reloading the Video:
videoPlayer.load();
Ensures that the video player recognizes the new source and type.
Benefits of These Modifications
-
Enhanced Flexibility:
Users can now upload and play videos of any supported format, not just MP4.
-
Improved User Experience:
Automatic handling of different video types reduces potential errors and ensures smoother playback.
-
Scalability:
The player can easily accommodate new video formats as browser support evolves.
-
Maintained Playlist Functionality:
Playlists remain fully functional, allowing users to manage and watch their video collections seamlessly.
Conclusion
By dynamically setting the video source and type based on the user's selected file, your video player becomes versatile and capable of handling a wide range of video formats. This approach leverages the browser's inherent capabilities to manage different media types, providing a robust and user-friendly experience.