简体   繁体   中英

Raspberry Pi and Mplayer sound loop error

I'm trying to play a 1sec sound in loop using mplayer . When I run the code it crashes the raspberry os. I noticed that some times multiple instances of the mplayer processes were hanging in the task manager so I've added code to get the process id pidof and kill it.
But the process keep appearing multiple times, and raspberry keeps crashing after some loops.

Also, some times it seems the sound is overlapped (probably because of the multiple instances of the process)

import os
import time
import serial

# arduino stuff
ser = serial.Serial('/dev/ttyACM0', 9600)

while True:
    os.system('mplayer -really-quiet /home/pi/Desktop/sound.mp3 &')
    time.sleep(1.5)
    ser.write('1') # send a signal to arduino 
    a = os.popen('pidof mplayer').read()
    if(a != ''):
        os.system('sudo kill ' + str(a))

Note: I've tried to use other players, like mpg123 , but the problem is exactly the same.

If your sound file is any time longer than your sleep time of 1.5 seconds, it is natural that an endless number of processes builts up, because you are running the mplayer in the background, as can be seen from the trailing '&'.

Killing the processes is a bit of a hack. And it introduces the problem, that you open a file-like object with os.popen() which you never close.

Rather you should trim your sound file to the length you want to have it play and remove the '&' at the end of the command line. As an alternative to trimming the sound file you may find an option of mplayer limiting the time it plays the tune.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM