jfranz
jfranz

Reputation: 13

Download YouTube video using Python, youtube-dlp and video/audio formats

I am writing a backend server in Flask that on demand uses youtube-dlp to provide users with the direct download link to audio and video formats (including audio).

The code I wrote succeeds in generating and displaying all the links on screen, the problem is that once the client clicks on links, they are redirected to a page where the audio or video can be played and downloaded.

I would like the video/audio download to occur once the client clicks on the link, without being redirected to a further page.

Below is the code:

app.py

from flask import Flask, jsonify, request, render_template
import yt_dlp

app = Flask(__name__)

def get_download_links(video_url):
    ydl_opts = {
        'format': 'best',
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(video_url, download=False)

        video_formats = []
        audio_formats = []
        for format in info['formats']:
            if 'url' in format:
                if 'acodec' in format and format['acodec'] != 'none':
                    audio_formats.append({
                        'format_id': format['format_id'],
                        'url': format['url'],
                    })
                else:
                    video_formats.append({
                        'format_id': format['format_id'],
                        'url': format['url'],
                    })

    return video_formats, audio_formats, info['title']

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/get_download_links', methods=['GET'])
def get_download_links_api():
    video_url = request.args.get('video_url')

    if not video_url:
        return jsonify({"error": "Il parametro 'video_url' è richiesto."}), 400

    video_formats, audio_formats, video_title = get_download_links(video_url)
    return jsonify({
        'video_formats': video_formats,
        'audio_formats': audio_formats,
        'video_title': video_title
    })

if __name__ == '__main__':
    app.run(debug=True)

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Download Links</title>
</head>
<body>
    <h1>Download Links</h1>
    <form id="video-form">
        <label for="video-url">Inserisci il link del video di YouTube:</label>
        <input type="text" id="video-url" required>
        <button type="submit">Genera link di download</button>
    </form>
    <div id="video-links"></div>
    <div id="audio-links"></div>

    <script src="{{ url_for('static', filename='js/main.js') }}"></script>
</body>
</html>

main.js

document.addEventListener('DOMContentLoaded', function() {
    function createDownloadLink(url, filename) {
        var link = document.createElement('a');
        link.href = url;
        link.download = filename;
        link.textContent = 'Download';
        link.style.display = 'block'; // Nasconde i link di download precedenti
        link.style.marginTop = '10px'; // Aggiunge uno spazio tra i link

        return link;
    }

    function displayVideoLinks(videoFormats) {
        var videoLinksDiv = document.getElementById('video-links');
        videoLinksDiv.innerHTML = '<h2>Video Download Links</h2>';

        videoFormats.forEach(function(format) {
            var link = createDownloadLink(format.url, format.format_id + '.mp4');
            videoLinksDiv.appendChild(link);
        });
    }

    function displayAudioLinks(audioFormats) {
        var audioLinksDiv = document.getElementById('audio-links');
        audioLinksDiv.innerHTML = '<h2>Audio Download Links</h2>';

        audioFormats.forEach(function(format) {
            var link = createDownloadLink(format.url, format.format_id + '.mp3');
            audioLinksDiv.appendChild(link);
        });
    }[enter image description here](https://i.sstatic.net/bWveQ.png)

    function getDownloadLinks(videoUrl) {
        fetch('/get_download_links?video_url=' + encodeURIComponent(videoUrl))
            .then(response => response.json())
            .then(data => {
                displayVideoLinks(data.video_formats);
                displayAudioLinks(data.audio_formats);
            })
            .catch(error => console.error('Error:', error));
    }

    var form = document.getElementById('video-form');
    form.addEventListener('submit', function(event) {
        event.preventDefault();
        var videoUrlInput = document.getElementById('video-url');
        var videoUrl = videoUrlInput.value.trim();
        if (videoUrl !== '') {
            getDownloadLinks(videoUrl);
        }
    });
});

Some screens [[Flow](https://i.sstatic.net/rGbiN.png)](https://i.sstatic.net/8Jqwp.png)

I expect that once the link/button is clicked instead of being redirected to a page with the video/audio playback downloadable from the client, the video/audio is downloaded once the linl/button is clicked.

Upvotes: 1

Views: 366

Answers (1)

Pragati Maurya
Pragati Maurya

Reputation: 1

Try using this to Download the file when clicking on the link (instead of navigating to the file):

<a href="<Download link here>" download>

Upvotes: 0

Related Questions