Youtube to mp3 code

Converting YouTube to MP3 format involves several steps, including downloading the video and extracting the audio. You can achieve this using various libraries available in Python, such as youtube_dl and moviepy.

Click here to

import youtube_dl

Here, we import the youtube_dl library, which is a powerful tool for downloading videos from various websites including YouTube.

def download_video(url):

This line defines a function called download_video which takes a single parameter url, representing the URL of the YouTube video we want to download.

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

Here, we define a dictionary ydl_opts which contains options for the downloader. We specify that we want to download the best audio available ('bestaudio/best'). We also specify postprocessing options to extract the audio using FFmpeg and encode it into MP3 format with a preferred quality of 192 kbps; this completes the Youtube to mp3.

Youtube DL Download Function

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:[url])

This block of code creates a YoutubeDL object with the options specified in ydl_opts, and then calls the download method with the provided YouTube video URL. This initiates the downloading and conversion process.

if __name__ == "__main__":
    youtube_url = input("Enter the YouTube video URL: ")

This part of the code is executed when the script is run as the main program. It prompts the user to input a YouTube video URL. Once the URL is entered, it calls the download_video function with the provided URL, initiating the download and conversion process.

To use this script, you need to have Python installed on your system along with the youtube_dl library. You can run the script, input the YouTube video URL when prompted, and the script will download the video from YouTube and extract the audio in MP3 format.

Remember to respect the terms of service of YouTube and ensure that you have the necessary permissions to download and use the content.


Youtube video and audio downloader code using Streamlit!

This Python code is a Streamlit application that allows users to download YouTube videos and audio. Let’s break down the code step by step:

  1. Importing Libraries:
from io import BytesIO 
from pydub import AudioSegment 
import streamlit as st 
from pytube 
import YouTube 
import os
  • BytesIO: Used for handling binary data in memory.
  • AudioSegment: Used to handle audio data for conversion.
  • streamlit: A library for creating web applications with Python.
  • YouTube: A library for accessing YouTube videos.
  • os: Operating system dependent functionality (though not used in this code).

Download Function for youtube to mp3 or mp4:

  • This function takes a YouTube video URL and an optional parameter convert_to_mp3, which defaults to False.
  • It uses pytube to get information about the video and streamlit to display the information and provide download buttons.
  • If convert_to_mp3 is True, it converts the video to MP3 format using pydub and provides a download button for the MP3 file.
  • Finally, it provides a download button for the original video.
def download_youtube_video(video_url, convert_to_mp3=False):
        yt = YouTube(video_url)
        st.write("Video Title:", yt.title)

        stream = yt.streams.get_highest_resolution()

        # Initialize a BytesIO object to store the video data
        buffer_v = BytesIO()

        st.write("Download complete!")
        if convert_to_mp3:
            # Initialize a BytesIO object to store the video data
            # buffer_a = BytesIO()
            st.write("Converting to MP3...")
            # Using pydub to read audio data from the buffer
            audio = AudioSegment.from_file(buffer_v, format="mp4")

            # Convert audio to mp3 (youtube to mp3) format and then save it to a new buffer
            buffer_a = BytesIO()
            audio.export(buffer_a, format="mp3")
            st.write("Conversion complete!")

            # Download button for MP3
            st.write("Download Audio:")
            st.download_button(label="Download Audio", data=buffer_a.getvalue(), file_name=f"{yt.title}.mp3")
        # Download button
        st.write("Download Video:")
        st.download_button(label="Download Video", data=buffer_v.getvalue(), file_name=f"{yt.title}.mp4")
    except Exception as e:
        st.error(f"An error occurred: {e}")

Main Function for Youtube to mp3 or mp4:

def main():
    st.title("YouTube Video Downloader")
    video_url = st.text_input("Enter YouTube Video URL:")
    if video_url:
        convert_to_mp3 = st.checkbox("Convert to Audio")
        download_youtube_video(video_url, convert_to_mp3)
  • This function sets up the Streamlit application’s title and takes input from the user for the YouTube video URL.
  • If a URL is provided, it checks if the user wants to convert the video to audio and then calls the download_youtube_video function.

Using BytesIO for buffer memory in video and audio

let’s break down how the BytesIO object and buffers work in Python:

  1. BytesIO Object:
  • BytesIO is a class provided by the io module in Python.
  • It allows you to treat a byte buffer in memory as a file-like object.
  • You can write binary data to it as if you were writing to a file, and you can read from it similarly.
  • It’s particularly useful when you need to work with binary data in memory without having to write it to disk.

Working with BytesIO:

  • To use BytesIO, you typically create an instance of it by calling BytesIO() with optional initial data.
  • You can write binary data to a BytesIO object using its write() method, and you can read from it using its read() method.
  • After writing data, you may need to rewind the position to the beginning of the buffer using the seek() method if you want to read from the start again.


  • A buffer is a temporary memory storage area.
  • Buffers are used to hold data temporarily while it is being moved from one place to another.
  • In the context of BytesIO, it’s used to store binary data in memory before it’s written to a file or processed further.

Binary Data:

  • Binary data consists of sequences of bytes, each representing a piece of information such as characters, numbers, or other data types.
  • In Python, binary data is typically represented using bytes or byte arrays.

Working with Binary Data and BytesIO:

  • When working with binary data, you can use BytesIO to handle it in memory.
  • For example, you can read binary data from a file using Python’s file I/O operations and then write it to a BytesIO object for further processing without having to save it to disk.
  • Similarly, you can create binary data in memory using BytesIO, manipulate it as needed, and then write it to a file or use it in other parts of your code.

In the provided code, BytesIO objects are used to store binary data representing video and audio content downloaded from YouTube. This allows the code to handle the data in memory without writing it to disk first. The buffer_v object stores video data, while buffer_a stores audio data after conversion. These buffers are then used to provide download functionality via Streamlit’s download_button function.

Overall, this code provides a simple interface for users to download YouTube videos either in their original format or as MP3 files if they choose to convert them.

Need more python app ideas? Check out: dice roller app or mm to inches app

2 thoughts on “Youtube to mp3 code

Leave a Reply

Your email address will not be published. Required fields are marked *