Play audio with VLC in Python.
This will work on any Linux distribution
A working Linux install with Python and VLC.
- # – requires given linux commands to be executed with root privileges either directly as a root user or by use of
- $ – requires given linux commands to be executed as a regular non-privileged user
There are plenty of ways to play audio files with Python. It really depends on your application, but the easiest way, by far, is to use the bindings for VLC to control VLC with Python, and play your files.
With VLC, you don’t need to worry about codecs and file support. It also doesn’t require too many complicated methods, and/or objects. So, for simple audio playback, VLC is best.
Get The VLC Bindings
The VLC bindings are actually developed and maintained by VLC. That said, the easiest way is still to use
# pip install python-vlc
Of course, if this is for a single project, use
Set Up Your File
Creating your file is very simple. You only need to import the VLC module.
That’s really all. You can use the module to create
MediaPlayer instances, and that’s what’s necessary to play audio.
Create A Media Player Object
Again, the VLC module is super easy to use. You only need to instantiate a
MediaPlayer object and pass it the audio file that you want to play. VLC can handle virtually any file type, so you don’t need to worry about compatibility.
player = vlc.MediaPlayer("/path/to/file.flac")
Play A Song
Playing a file from an existing object is even easier. You only need to call the
play method on the object, and Python will begin playing it. When the playback finishes, it will stop. There’s no looping or any nonsense like that.
Stopping And Pause
The VLC bindings make it easy to stop or pause a file once you’ve started playing it too. There is a
pause method that will pause playback if the file is playing.
If the player is already paused, calling the method again will resume playback.
To stop a file altogether, call the
Looping And “Playlists”
You can actually create pseudo-playlists with this, and loop through the songs that you’ve added. It would only take a basic
playlist = ['/path/to/song1.flac', '/path/to/song2.flac', 'path/to/song3.flac'] for song in playlist: player = vlc.MediaPlayer(song) player.play()
That’s obviously very rudimentary, but you can see how Python can script VLC.
VLC isn’t the only solution for playing audio with Python, and it certainly isn’t the best in every situation, but it is very good for a lot of basic use cases. The greatest bonus of using VLC is the unbeatable simplicity.
- Install the Python VLC bindings with
pipin a virtual environment.
- Create a Python file and import the VLC bindings.
- Instantiate a player object to play a file.
- Play that file.
- Play the file again. Pause and resume playback.
- Create a loop to play multiple files in order.
- Challenge: Generate a list of files using Python modules to interact with directories on your system. Play them as a playlist.