Skip to content
Advertisement

python-vlc running out of memory after playing multiple songs

I am writing a python program, running on a raspberry pi (PI 3 A+), that plays a song every 10 minutes. I am using python-vlc to play the song through the pi’s headphone jack.

PlaySong() is a function that gets called (successfully) every 10 minutes.

import vlc

def PlaySong():
    p = vlc.MediaPlayer("file:///home/pi/music.mp3")
    p.play()

This works as expected the first 6 times. After 6 times, it doesn’t play anymore, and instead throws this error:

mmap() failed: cannot allocate memory

This happens even when I change it from every 10 minutes to every 2 minutes, so it doesn’t have to do with the amount of time.

Task Manager shows that there is still plenty of memory available on the pi itself.

Any suggestions?

Advertisement

Answer

It is running out of memory because the media player was not released. The solution is to add in p.release() after playing the song. This will stop the song immediately, so we will want to add in time.sleep() before p.release().

The final code would look something like this:

import time
import vlc
def PlaySong():
    p = vlc.MediaPlayer("file:///home/pi/music.mp3")
    p.play()
    time.sleep(5) #play for 5 seconds
    p.release()

If you want the mp3 to play for the entire duration of the song, you can loop until it’s done playing, like this:

import time
import vlc
def PlaySong():
    p = vlc.MediaPlayer("file:///home/pi/music.mp3")
    p.play()
    time.sleep(1) #this is necessary because is_playing() returns false if called right away
    while p.is_playing():
        time.sleep(1)
    p.release()
Advertisement