Cur*_*Cat 5 python subprocess python-multithreading raspberry-pi
我正在尝试使用 RPi 实现无线电播放器。目标是设置播放列表并在播放列表填充后开始播放。一旦停止代码被执行,播放器和收音机进程就会退出。
无线电进程很好地终止,但播放器进程即使在调用终止后仍然保持等待。如果再次调用停止代码,则播放器进程终止
尝试的事情:
玩家代码:
while playlist:
player = subprocess.Popen(
["avconv", "-i", "Music/%s" % playlist[0], "-f", "s16le", "-ar",
"22.05k", "-ac", "1", "-"], stdout=subprocess.PIPE)
radio = subprocess.Popen(["./pifm", "-", freq], stdin=player.stdout)
radio.wait()
print "************ exiting from radio :)"
player.wait()
print "************ exiting from player :)"
playlist.pop(0)
player = None
radio = None
Run Code Online (Sandbox Code Playgroud)
播放器停止代码(从另一个线程调用):
print "************ stop requested"
if radio and radio.poll() is None:
print "************ terminating radio :)"
radio.terminate()
if player and player.poll() is None:
print "************ terminating player :)"
player.terminate()
Run Code Online (Sandbox Code Playgroud)
选择:
另一种选择是为广播和播放器的点播过程提供一个持久的接收器
def start_radio():
global radio
radio = subprocess.Popen(["./pifm"...], stdin=subprocess.PIPE)
def play():
global player
while playlist and radio:
player = subprocess.Popen(["avconv"...], stdout=radio.stdin)
player.wait()
playlist.pop(0)
def stop():
if player and player.poll() is None:
print "************ terminating player :)"
player.terminate()
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,调用 player.terminate() 会关闭播放器,同时在广播过程中重复播放最后一个数据包(如卡住的记录)。这个卡住的唱片会一直播放,直到我开始一个新的播放器或终止收音机。
正如 @JFSebastian 提到的,使用player.stdout.close()有效。整个代码库发布在这里https://github.com/hex007/pifm_server
所以最终的代码看起来像这样
while playlist:
player = subprocess.Popen(
["avconv", "-i", "Music/%s" % playlist[0], "-f", "s16le", "-ar",
"22.05k", "-ac", "1", "-"], stdout=subprocess.PIPE)
radio = subprocess.Popen(["./pifm", "-", freq], stdin=player.stdout)
player.stdout.close()
radio.wait()
player.wait()
if stop_requested:
stop_requested = False
break
playlist.pop(0)
player = None
radio = None
Run Code Online (Sandbox Code Playgroud)
以及停止代码:
stop_requested = True
if radio and radio.poll() is None:
radio.terminate()
if player and player.poll() is None:
player.terminate()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1320 次 |
| 最近记录: |