File size: 2,310 Bytes
f57951a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9cea26
 
 
 
 
 
 
f57951a
 
 
 
 
 
 
 
a9cea26
 
f57951a
 
 
 
 
 
 
 
 
 
5a51f76
f57951a
5a51f76
a9cea26
5a51f76
f57951a
 
 
 
 
a9cea26
 
 
 
f57951a
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""This is the main module of the streamlit app that allows the user to download youtube videos as mp3 files."""
import streamlit as st
from yt_dlp import YoutubeDL
import os
from io import BytesIO
from datetime import datetime

URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc']


ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
    'outtmpl': 'audio'
}

def download_video(url):
    with YoutubeDL(ydl_opts) as ydl:
        print(url)
        error_code = ydl.download([url])
        info = ydl.extract_info(url, download=False)
        print(error_code)
    return error_code, info

def clean_files():
    if os.path.isfile('audio'):
        os.remove('audio')
    if os.path.isfile('audio.mp3'):
        os.remove('audio.mp3')


def main():
    """This method has a text input field, radio button and a button for downloading the video as mp3."""
    st.title('Youtube to mp3')
    st.write('Enter the url of the youtube video you want to download')
    url = st.text_input('URL')

    if st.button('Download video'):
        with st.spinner('Downloading video'):
            clean_files()
            
            error_code, info = download_video(url)

            st.session_state['latest_video'] = url
            st.session_state['latest_title'] = info['fulltitle']

            if error_code:
                st.error('Error downloading video')
            else:
                st.success('Downloaded video')
    
    if os.path.isfile('audio.mp3') and st.session_state.get('latest_video'):
        video_url = st.session_state.get('latest_video', '/')
        video_title = st.session_state.get('latest_title', '/')

        st.write(f"Last downloaded video is: {video_title} with url {video_url}")
        st.audio('audio.mp3')
        buffer = BytesIO()
        with open('audio.mp3', 'rb') as f:
            buffer.write(f.read())
        timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        st.download_button(label='Download mp3',
                           data=buffer.getvalue(),
                           file_name=f"{video_title.replace(' ', '-')}.mp3",
                           mime="audio/mp3")

if __name__ == '__main__':
    main()