'How to dynamically change self variables, parameters, args... in multiprocessing?
I don't know much of Python yet, but I'm trying to create an app that controls multiple streams of sound simultaneously (It has to do with binaural beats, noise and the brain). Given that I would like to control the volume and state of each of the tracks separately, I think that I need to use multiprocessing module. The first of those streams is a simple background music. I would like the user to pause it whenever he wants and I'm using pygame module.
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()
This doesn't work. The state doesn't get modified whenever I input pause or stop. Any help is welcomed. Thank you so much in advance.
Solution 1:[1]
Since multiprocessing module creates separate Python processes, it is not possible to share variables in an easy way.
In case you would like to share variables yet still parallelize some of your computing, you should look into the built-in threading module.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Piotr Ostrowski | 
