How do I instantiate a pygame.mixer object when I instantiate my object so I can control it after my program threads?
My application requires me to thread a program loop and a flask app, both operating on the same instantiated object.
from radio.radio import Radio
from flask import Flask, request, jsonify
import threading
def program_loop(controller_obj):
while True:
self.act_on_order(self.receive_order())
if self.mode != config.MODE_OFF:
self.check_for_new_audio()
time.sleep(config.RADIO_LOOP_DELAY)
controller_obj = Radio()
# threaded program_loop(controller_obj)
#
thread_obj = threading.Thread(target=program_loop, args=(controller_obj,), daemon=True)
thread_obj.start()
# flask controller
#
app = Flask(__name__) # Create the server object
@app.route("/cmd")
def cmd():
order_obj = request.args.to_dict(flat=True)
return jsonify(controller_obj.act_on_order(order_obj))
app.run(debug=True)
The object is instantiated and then passed to the two branches of the program. So far, so good.
However, the object needs to use pygame.mixer. The pygame package is imported with the object module (Radio) and apparently creates two instances. I get two separate audio streams from the two threads, rather than one that I can control from either.
import pygame
class Radio(Controller):
"""Radio controller class."""
def __init__(self):
"""Initialize."""
super().__init__()
# used by audio mixer
pygame.mixer.init()
pygame.mixer.music.set_volume(float(config.RADIO_VOLUME))
def act_on_order(self, order):
"""Take action based on order."""
I know from the pygame docs that pygame.mixer.init returns None. But is there a way I can create a handle that I can control my mixer from either thread?
EDIT1: Someone saw right through my question to the actual question I was getting at, which was "why is my program launching two streams of music, with one I can't pause or alter?" The answer was a flask issue, not a pygame issue: In dev mode, flask fires off two threads to allow for reloading. This is described in here in SO#25504149. The answer was simply adding use_reloader=False to my app.run call.
app.run(port=8080, debug=config.DEBUG, use_reloader=False)
It still doesn't answer the literal question (how do I get a handle on the pygame.mixer) which I'm sure will come up for me and maybe others later. But perhaps this opens up an opportunity for someone to say that if you thread after you've instantiated pygame.mixer, it is available to all your threads...