如何动态更改自变量、参数、args…在多处理?



我对Python了解不多,但我正在尝试创建一个同时控制多个声音流的应用程序(它与双耳节拍,噪音和大脑有关)。考虑到我想分别控制每个轨道的音量和状态,我认为我需要使用多处理模块。第一个流是简单的背景音乐。我希望用户可以随时暂停它,我使用pygame模块。

import pygame
import time
import os
import multiprocessing
class play_music:
def __init__(self, path="", name=""):
self.state="" #pause, play, stop
self.name=name #name of the song
self.path=path #path of the song
def play_music(self):
path=self.path
pygame.init()
pygame.mixer.music.load(path)
pygame.mixer.music.play()
print (f"Playing {path}...")
while True:

if self.state=="pause":
pygame.mixer.music.pause()
self.state=""
while self.state=="":
if self.state == "continue":
pygame.mixer.music.unpause()
elif self.state=="stop"():
pygame.mixer.music.stop()
break
elif self.state=="stop":
pygame.mixer.music.stop()
break

def main():
task = ""
while not ( task == "meditacion" or task == "estudio"):
task = input ("Introduce que vas a hacer (meditacion, estudio): ").rstrip()

name ="non-existing track"
while not (os.path.exists(f"musica/{task}/{name}")):
name = input ("Introduce pista musical: ").rstrip()

path = f"musica/{task}/{name}"
print (f"Correct track. Path: {path}")

music = play_music()
music.path=path
music.name=name

p1 = multiprocessing.Process(target=music.play_music)
p1.start()

time.sleep(3) #for letting the process start correctly
while True:
music.state=input("pause, stop?: ")

if __name__=="__main__":
main()

这行不通。无论何时我输入pause或stop,状态都不会被修改。欢迎任何帮助。提前谢谢你。

由于multiprocessing模块创建了单独的Python进程,因此不可能以简单的方式共享变量。

如果您想共享变量,但仍然并行处理一些计算,您应该查看内置的threading模块。

最新更新