YouTube to MP3 Using Python

Turn your favorite YouTube video to MP3

  • 12 January 2023

Introduction

I recently purchased a new Garmin sports watch allowing for audio playback! That's right - a small watch singing through my long runs ⌚! Unfortunately the audio needs to be in MP3 format, and manually uploaded.

This inspired the creation of a Python application that takes any YouTube video as a URL, and converts it to an MP3. Since YouTube caters for singles, soundtracks, podcasts and virtually any digital content - there's a strong incentive to create this application. The result, albeit visualised through Dash, is shown below. Try it out!


Currently experiencing issues due to server-side timeouts! Something interesting that I need to solve!



If you're interested in how this was done using Python, then read below

Requirements and Imports

pytube and pydub are required. This can be easily installed by copying and pasting the following into Command Prompt:


	pip install pytube, pudub

The imports are shown below. pytube is used to stream YouTube content. pydub allows for audio conversions. io has BytesIO used for buffering.


	from pytube import YouTube # Used to stream YT
	from pydub import AudioSegment # Used for audio conversion
	from io import BytesIO # Used for memory storage

Main Code

The YouTube content needs to be streamed, audio stripped, downloaded, and temporarily buffered in a BytesIO object. Once stored, the memory pointer moves to the start.


	yt = YouTube(YOUTUBE_URL)
	audio = yt.streams.filter(only_audio=True).first() # Stream audio
	audio_bytes = BytesIO() # Create 
	audio.stream_to_buffer(audio_bytes)
	audio_bytes.seek(0)

The object audio stores an MP4 file. The last step is to convert it to MP3, which is stored in a new BytesIO buffer, before writing the result to a given path.


	sound = AudioSegment.from_file(file=audio_bytes).export(BytesIO(), 'mp3')
	with open('path/to/file', 'wb') as f:
    	f.write(sound.getbuffer())

Complete code in my GitHub repository (with exception additions).

Conclusion

You now have your very own YouTube to MP3 Audio converter!