Search code examples
pythonlinuxbackground-processmplayer

mplayer does not work when Python script run in background


I have a python script that plays some audio files with mplayer. This is how I call mplayer in the code:

subprocess.call(["mplayer","-msglevel","all=-1",audiofile])

it works fine if I run the script in foreground... However if I run the script in background like

sudo python script.py &

I cannot get any audio... why? How to fix it?


Solution

  • According to Mplayer FAQ:

    Q: How can I run MPlayer in the background?

    A: Use:

      mplayer options filename < /dev/null &
    

    In python, use stdin argument to pass null file.

    import os
    import subprocess
    
    with open(os.devnull, 'wb') as nul:
        subprocess.call(['mplayer', '-msglevel', 'all=-1', audiofile], stdin=nul)