| 1 |
Launching the audio processing in a separated thread |
| 2 |
============================================================================================================================================ |
| 3 |
|
| 4 |
|
| 5 |
**08-multiple-threads.py** |
| 6 |
|
| 7 |
This program launches an audio process in a separated thread with the |
| 8 |
subprocess module and sends parameters to its standard input to control |
| 9 |
the sound playback. |
| 10 |
|
| 11 |
.. code-block:: python |
| 12 |
|
| 13 |
import os |
| 14 |
import sys |
| 15 |
import time |
| 16 |
import random |
| 17 |
import subprocess |
| 18 |
|
| 19 |
# Get the python command according to the current operating system. |
| 20 |
if sys.platform.startswith("win"): |
| 21 |
PYTHON_EXE = "py -%d.%d" % (sys.version_info[0], sys.version_info[1]) |
| 22 |
else: |
| 23 |
PYTHON_EXE = "python%d.%d" % (sys.version_info[0], sys.version_info[1]) |
| 24 |
|
| 25 |
# Path of the python file to run in the subprocess. |
| 26 |
script_path = os.path.join(os.path.expanduser("~"), "08_multiple_threads_process.py") |
| 27 |
|
| 28 |
# Thread's processing... Soundfile player + delay + reverb. |
| 29 |
script = """ |
| 30 |
from pyo import * |
| 31 |
|
| 32 |
s = Server(duplex=0).boot() |
| 33 |
|
| 34 |
sf = SfPlayer('../snds/snd_1.aif', mul=0.7) |
| 35 |
dd = SmoothDelay(sf, delay=0.25, feedback=0.5) |
| 36 |
rv = STRev(sf+dd, inpos=0.50, revtime=1.5, cutoff=5000, bal=0.25).out() |
| 37 |
|
| 38 |
s.start() |
| 39 |
""" |
| 40 |
|
| 41 |
# Create the python file to run in the subprocess. |
| 42 |
f = open(script_path, "w") |
| 43 |
f.write(script) |
| 44 |
f.close() |
| 45 |
|
| 46 |
# Launch an interactive python (-i flag) in a subprocess and store a |
| 47 |
# reference to the standard input to pass message to the running process. |
| 48 |
pipe = subprocess.Popen( |
| 49 |
["%s -i %s" % (PYTHON_EXE, script_path)], shell=True, universal_newlines=True, stdin=subprocess.PIPE, |
| 50 |
).stdin |
| 51 |
|
| 52 |
# Wait for the audio server to be ready. |
| 53 |
time.sleep(2) |
| 54 |
|
| 55 |
# Send events to the subprocess. |
| 56 |
for i in range(20): |
| 57 |
# Randomly choose a sound (snd_1.aif to snd_6.aif). |
| 58 |
snd = "../snds/snd_%d.aif" % random.randrange(1, 7) |
| 59 |
|
| 60 |
# Replace the sound and start the playback. |
| 61 |
pipe.write("sf.path = '%s'\ndump = sf.play()\n" % snd) |
| 62 |
pipe.write("dd.delay = %f\n" % random.uniform(0.1, 0.5)) |
| 63 |
pipe.flush() |
| 64 |
|
| 65 |
# Wait some time before the next event. |
| 66 |
time.sleep(random.uniform(0.5, 1)) |
| 67 |
|
| 68 |
# Stop the audio Server before exiting. |
| 69 |
pipe.write("s.stop()\ntime.sleep(0.25)\n") |
| 70 |
|
| 71 |
# Close the subprocess. |
| 72 |
pipe.close() |
| 73 |
|
| 74 |
# Delete the python file. |
| 75 |
os.remove(script_path) |
| 76 |
|