FreeDATA/tnc/audio.py

74 lines
2.1 KiB
Python
Raw Normal View History

import json
2022-02-17 13:25:22 +00:00
import sys
import multiprocessing
import sounddevice as sd
import atexit
atexit.register(sd._terminate)
2022-04-11 09:03:54 +00:00
def get_audio_devices():
2022-02-15 17:10:14 +00:00
"""
return list of input and output audio devices in own process to avoid crashes of portaudio on raspberry pi
2022-04-11 09:03:54 +00:00
also uses a process data manager
"""
2022-02-19 19:45:57 +00:00
# we need to run this on windows for multiprocessing support
# multiprocessing.freeze_support()
2022-04-11 09:03:54 +00:00
# multiprocessing.get_context('spawn')
2022-02-17 13:25:22 +00:00
# we need to reset and initialize sounddevice before running the multiprocessing part.
# If we are not doing this at this early point, not all devices will be displayed
sd._terminate()
sd._initialize()
2022-04-11 09:03:54 +00:00
2022-02-19 19:45:57 +00:00
with multiprocessing.Manager() as manager:
2022-04-11 09:03:54 +00:00
2022-02-19 19:45:57 +00:00
proxy_input_devices = manager.list()
proxy_output_devices = manager.list()
2022-04-11 09:03:54 +00:00
# print(multiprocessing.get_start_method())
p = multiprocessing.Process(
target=fetch_audio_devices, args=(proxy_input_devices, proxy_output_devices)
)
2022-02-19 19:45:57 +00:00
p.start()
p.join()
2022-04-11 09:03:54 +00:00
return list(proxy_input_devices), list(proxy_output_devices)
def fetch_audio_devices(input_devices, output_devices):
"""
get audio devices from portaudio
2022-04-11 09:03:54 +00:00
Args:
input_devices: proxy variable for input devices
output_devices: proxy variable for outout devices
Returns:
"""
2022-04-11 09:03:54 +00:00
devices = sd.query_devices(device=None, kind=None)
index = 0
for device in devices:
2022-04-11 09:03:54 +00:00
# for i in range(0, p.get_device_count()):
2022-02-19 19:45:57 +00:00
# we need to do a try exception, beacuse for windows theres no audio device range
try:
name = device["name"]
2022-04-11 09:03:54 +00:00
maxOutputChannels = device["max_output_channels"]
maxInputChannels = device["max_input_channels"]
except Exception as e:
print(e)
maxInputChannels = 0
maxOutputChannels = 0
2022-04-11 09:03:54 +00:00
name = ""
if maxInputChannels > 0:
input_devices.append({"id": index, "name": str(name)})
if maxOutputChannels > 0:
output_devices.append({"id": index, "name": str(name)})
index += 1