Creating a fully client-side web application that allows users to download a playlist of media files (mp3 or mp4) as a ZIP archive is feasible using HTML, CSS, and JavaScript. Below is a complete implementation that accomplishes this.
Important Notes:
-
CORS Restrictions: The ability to fetch media files depends on the server hosting those files allowing cross-origin requests. If the media sources do not permit CORS, fetching them directly from the browser will fail.
-
Browser Limitations: Large files or numerous files may cause performance issues or exceed browser memory limits.
-
Media Conversion: This implementation assumes that the media files are already in the desired format (mp3 or mp4), as converting formats client-side is beyond the scope of this example.
-
User Responsibility: Users need to provide direct URLs to the media files. URLs to streaming services like YouTube require server-side processing which isn't handled here.
Here's the complete code for the web application:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Playlist Downloader</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f2f2;
padding: 20px;
}
h1 {
text-align: center;
}
.container {
max-width: 800px;
margin: auto;
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.playlist-input {
width: 100%;
height: 150px;
padding: 10px;
font-size: 14px;
margin-bottom: 20px;
border: 1px solid #ccc;
border-radius: 4px;
resize: vertical;
}
.options {
margin-bottom: 20px;
}
.options label {
margin-right: 15px;
}
button {
background-color: #4CAF50;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #45a049;
}
.status {
margin-top: 20px;
padding: 10px;
background-color: #e7f3fe;
border-left: 6px solid #2196F3;
display: none;
}
.status.show {
display: block;
}
</style>
</head>
<body>
<div class="container">
<h1>Playlist Downloader</h1>
<textarea id="playlist" class="playlist-input" placeholder="Enter media URLs, one per line..."></textarea>
<div class="options">
<label>
<input type="radio" name="format" value="mp3" checked> MP3
</label>
<label>
<input type="radio" name="format" value="mp4"> MP4
</label>
</div>
<div class="options" id="resolutionOptions">
<label for="resolution">Select Resolution (for MP4): </label>
<select id="resolution">
<option value="480">480p</option>
<option value="720">720p</option>
<option value="1080">1080p</option>
<option value="highest">Highest Available</option>
</select>
</div>
<button id="downloadBtn">Download Playlist as ZIP</button>
<div id="status" class="status"></div>
</div>
<!-- JSZip Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js"></script>
<!-- FileSaver.js Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
const formatRadios = document.getElementsByName('format');
const resolutionOptions = document.getElementById('resolutionOptions');
const resolutionSelect = document.getElementById('resolution');
const downloadBtn = document.getElementById('downloadBtn');
const statusDiv = document.getElementById('status');
// Show or hide resolution options based on format selection
formatRadios.forEach(radio => {
radio.addEventListener('change', () => {
if (radio.value === 'mp4') {
resolutionOptions.style.display = 'block';
} else {
resolutionOptions.style.display = 'none';
}
});
});
// Initialize visibility
resolutionOptions.style.display = 'none';
downloadBtn.addEventListener('click', async () => {
const playlistText = document.getElementById('playlist').value.trim();
if (!playlistText) {
alert('Please enter at least one media URL.');
return;
}
const urls = playlistText.split('\n').map(url => url.trim()).filter(url => url);
if (urls.length === 0) {
alert('Please enter valid media URLs.');
return;
}
let selectedFormat = 'mp3';
formatRadios.forEach(radio => {
if (radio.checked) selectedFormat = radio.value;
});
let selectedResolution = resolutionSelect.value;
// Initialize JSZip
const zip = new JSZip();
// Update status
statusDiv.classList.add('show');
statusDiv.innerHTML = 'Starting download...';
for (let i = 0; i < urls.length; i++) {
const url = urls[i];
statusDiv.innerHTML = `Downloading (${i + 1}/${urls.length}): ${url}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch: ${response.statusText}`);
}
let blob = await response.blob();
// Optionally handle format and resolution here
// This example assumes that the provided URL already points to the correct format and resolution
// Extract filename from URL
let filename = url.split('/').pop().split('?')[0];
if (!filename) {
filename = `file_${i + 1}.${selectedFormat}`;
} else {
// Replace extension with selected format
filename = filename.replace(/\.[^/.]+$/, "") + `.${selectedFormat}`;
}
// Add file to zip
zip.file(filename, blob);
} catch (error) {
console.error(`Error downloading ${url}:`, error);
statusDiv.innerHTML += `<br>Error downloading ${url}: ${error.message}`;
}
}
statusDiv.innerHTML = 'Generating ZIP file...';
try {
const zipBlob = await zip.generateAsync({ type: 'blob' }, (metadata) => {
statusDiv.innerHTML = `Generating ZIP... ${Math.round(metadata.percent)}% completed`;
});
saveAs(zipBlob, 'playlist.zip');
statusDiv.innerHTML = 'Download ready!';
} catch (error) {
console.error('Error generating ZIP:', error);
statusDiv.innerHTML = `Error generating ZIP: ${error.message}`;
}
});
});
</script>
</body>
</html>
Explanation of the Implementation:
-
HTML Structure:
- Textarea: Allows users to input media URLs, one per line.
- Format Options: Radio buttons to select the desired format (
mp3 or mp4).
- Resolution Options: A dropdown to select the desired resolution for
mp4 files. This section is shown only when mp4 is selected.
- Download Button: Initiates the download process.
- Status Div: Displays the current status of the download and ZIP generation process.
-
CSS Styling:
- Provides a clean and responsive design with a centered container, styled inputs, and a visually distinct status area.
-
JavaScript Functionality:
- Event Listeners:
- Toggles the visibility of resolution options based on the selected format.
- Handles the click event on the download button.
- Download Process:
- Parses the entered URLs.
- Uses
fetch to retrieve each media file. This requires that the URLs support CORS.
- Adds each fetched file to a ZIP archive using
JSZip.
- Provides real-time status updates to the user.
- Generates the ZIP file and triggers a download using
FileSaver.js.
- Error Handling:
- Catches and displays errors if a media file can't be fetched or if there's an issue generating the ZIP.
-
External Libraries:
- JSZip: For creating ZIP archives client-side.
- FileSaver.js: For triggering the download of the generated ZIP file.
Usage Instructions:
-
Enter Media URLs:
- Paste or type the direct URLs to your
mp3 or mp4 media files into the textarea, placing each URL on a separate line.
-
Select Format:
- Choose between
MP3 and MP4. If MP4 is selected, additional resolution options will appear.
-
Select Resolution (if MP4):
- Choose the desired resolution. Note that this implementation assumes URLs point directly to media files of the selected resolution.
-
Download:
- Click the "Download Playlist as ZIP" button.
- The app will fetch each file, compile them into a ZIP archive, and prompt you to download the ZIP file.
Limitations and Considerations:
-
CORS Issues: If the media URLs do not allow cross-origin requests, the fetch will fail. Ensure that the media sources permit such access or host your media files on a server that does.
-
Browser Performance: Downloading large files or handling many files simultaneously may impact browser performance or exceed memory limits.
-
Format and Resolution Handling: This example does not perform actual format conversion or resolution changes. It assumes the provided URLs already point to the desired format and resolution. Implementing conversion would require more complex handling, often involving server-side processing or more advanced client-side libraries.
-
Security: Always be cautious when downloading files from untrusted sources to avoid security risks.
Conclusion
This implementation provides a straightforward, client-side solution to download a playlist of media files as a ZIP archive. While it covers the basic functionality, further enhancements such as format conversion, resolution adjustment, and improved error handling can be implemented based on specific requirements and the constraints of the browser environment.