Creating a YouTube to MP3/MP4 converter tool involves **frontend development** (HTML/CSS/JavaScript) and **backend development** (to handle YouTube API and conversion). Below is a step-by-step guide to build a tool similar to the one in your screenshot.
---
### **Step 1: Frontend Setup (HTML/CSS/JavaScript)**
Create a simple interface with an input field, buttons, and a result display.
#### **HTML (`index.html`):**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>YouTube to MP3/MP4 Converter</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>YouTube Converter</h1>
<div class="input-group">
<input type="text" id="youtubeUrl" placeholder="Paste YouTube URL here">
<button onclick="convert()">Convert</button>
</div>
<div id="result" class="hidden">
<h2 id="title">Title</h2>
<p id="duration">Duration: 00:00</p>
<div class="download-buttons">
<button onclick="downloadMP3()">Download MP3</button>
<button onclick="downloadMP4()">Download MP4</button>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
```
#### **CSS (`style.css`):**
```css
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background: #f0f0f0;
}
.container {
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
width: 500px;
}
.input-group {
margin-bottom: 20px;
}
input {
width: 70%;
padding: 10px;
margin-right: 10px;
}
button {
padding: 10px 20px;
background: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background: #45a049;
}
.hidden {
display: none;
}
.download-buttons {
margin-top: 20px;
}
.download-buttons button {
margin: 0 10px;
}
```
---
### **Step 2: Backend Setup (Python/Node.js)**
Use a backend to handle YouTube URL processing and conversion. Below is a **Python/Flask** example.
#### **Python Backend (`app.py`):**
```python
from flask import Flask, request, send_file
from pytube import YouTube
import os
from moviepy.editor import *
app = Flask(__name__)
@app.route('/convert', methods=['POST'])
def convert():
url = request.json['url']
try:
yt = YouTube(url)
audio_stream = yt.streams.filter(only_audio=True).first()
# Download audio
audio_path = audio_stream.download(filename="audio.mp4")
# Convert to MP3
clip = AudioFileClip(audio_path)
mp3_path = "output.mp3"
clip.write_audiofile(mp3_path)
clip.close()
# Get title and duration
title = yt.title
duration = yt.length
return {
"title": title,
"duration": duration,
"mp3_ready": True
}
except Exception as e:
return {"error": str(e)}
@app.route('/download/mp3')
def download_mp3():
return send_file('output.mp3', as_attachment=True)
if __name__ == '__main__':
app.run(debug=True)
```
---
### **Step 3: JavaScript Logic (`script.js`)**
Handle user interactions and communicate with the backend.
```javascript
async function convert() {
const url = document.getElementById('youtubeUrl').value;
if (!url) {
alert("Please paste a YouTube URL!");
return;
}
try {
const response = await fetch('http://localhost:5000/convert', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: url })
});
const data = await response.json();
if (data.error) {
alert(data.error);
return;
}
// Show result
document.getElementById('result').classList.remove('hidden');
document.getElementById('title').textContent = data.title;
document.getElementById('duration').textContent = `Duration: ${formatDuration(data.duration)}`;
} catch (error) {
alert("Conversion failed!");
}
}
function formatDuration(seconds) {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}
function downloadMP3() {
window.location.href = 'http://localhost:5000/download/mp3';
}
function downloadMP4() {
// Add MP4 logic here (similar to MP3)
alert("MP4 download coming soon!");
}
```
---
### **Step 4: Run the Tool**
1. Install dependencies:
```bash
pip install flask pytube moviepy
```
2. Start the backend:
```bash
python app.py
```
3. Open `index.html` in a browser.
---
### **Key Features Added:**
1. **URL Input & Convert Button**: Users paste YouTube URLs.
2. **Title & Duration Display**: Fetched from YouTube data.
3. **MP3/MP4 Download**: Uses `pytube` for downloading and `moviepy` for conversion.
4. **Error Handling**: Alerts for invalid URLs or failures.
---
### **Notes:**
- **Legal Compliance**: Ensure you comply with YouTube's Terms of Service and copyright laws.
- **Scalability**: For heavy traffic, use a cloud server (AWS/Heroku) and add rate-limiting.
- **MP4 Support**: Add similar logic for video download in the backend.
This is a basic version. Enhance it with loading spinners, progress bars, or a database to track conversions!