Mac miniで出力する3WAYチャンネルディバイダーをChat GPTに作ってもらった(※注意)
今回は、Mac miniとUSB DACを使って、2WAY/3WAYを切り替えられるチャンネルディバイダーを作ってみました。
といっても、プログラムを書いたのは私ではなくChatGPTです。
こちらが「こういうことをやりたい」と相談し、実際にMac miniで動作させ、問題があれば修正してもらうという方法で制作しました。
最終的にはMacの「Audio MIDI設定」で作成した「機器セット」を利用して、低音・中音・高音をそれぞれ別のDACに振り分けることができるようになりました。
※最初にお読みください(注意事項)
このプログラムはChatGPTで作成したコードです。Mac mini M4で動作を確認していますが、すべての環境で正常に動作する保証はありません。
不具合、音切れ、予期しない大音量などが発生する可能性があります。使用や改造、機器への接続は自己責任でお願いします。
特にツイーターなどを接続する場合は、ソフトウェアのフィルターだけでは十分に保護できません。適切な保護回路を使用し、最初は小音量で安全な構成から試してください。
本記事は自作オーディオの実験記録であり、専門的な音響測定によって性能を保証した製品ではありません。
チャンネルディバイダーとは?
音楽の信号を周波数帯域ごとに分け、異なるアンプやスピーカーへ送る仕組みです。
2WAY:低域と高域
3WAY:低域・中域・高域
通常は専用のDSP機器などで行いますが、今回はPythonを利用し、Mac miniで実現してみました。
用意するもの
Mac(動作確認はMac mini M4)
BlackHole 2ch(Mac内の音声データをキャプチャするソフト)
USB DACなどの出力機器(3WAYではステレオ3組分)
アンプ・スピーカー
Python 3
NumPy、SciPy、sounddevice、Tkinter
音声信号の流れ
音楽再生アプリからBlackHoleへ音声を送り、Pythonで周波数を分離してから、Macの機器セットを経由して各DACへ出力します。
3WAYなら、低域・中域・高域をそれぞれ別々のステレオ出力へ送ります。
ここで重要なのは、「複数出力装置」ではなく「機器セット」を使用することです。
制作中に起きた問題
最初は2WAYから開発しましたが、DACを個別に出力する方式を試したところ、バッファ不足によって音が正常に再生されなくなりました。
そこで、安定していた以前の構造に戻し、1つの機器セットに対して音声を出力する方式に変更しました。
これで安定して再生できるようになり、その後、機器セットに含まれるDACを名前で選択できるように改良しました。
今回の3WAY版は、その安定していた構造を引き継いでいます。
2WAY・3WAY切り替え機能
2WAYではクロスオーバー周波数を1つ、3WAYでは2つ設定できます。
3WAYの初期値は低域/中域が400Hz、中域/高域が3,000Hzです。
各帯域の音量は個別に調整でき、再生中でも周波数や音量を変更できます。
ただし、モードや出力先を変更するときは、一度再生を停止する必要があります。
ソースコードと注釈
プログラムはMac Channel Divider v0.8です。
主要な処理は以下のようになっています。
mac_aggregate_routes():機器セット内のDACとチャンネルを検出
design_filters():2WAY/3WAYの分離フィルターを作成
RealtimeEngine:音声の取得、周波数分離、チャンネルへの出力を実行
request_crossover():再生中の周波数変更
DividerApp:機器選択や音量調整を行う操作画面
分離フィルターには4次Linkwitz–Riley型を使用しています。
ソースコード全文は、記事末尾への掲載しています。
最後に
今回は自分のやってみたいことをChatGPTに相談し、コードを作ってもらいながら実機で試すという方法で制作しました。
プログラミングの専門家ではなくても、AIを使ってこんな実験ができるというのは面白いものです。
もちろん、AIが作ったコードだからといって、必ず正しく動作するとは限りません。実際、開発途中には音声が正常に再生されない問題もありました。
だからこそ、動作を確かめながら改良することが重要なのだと思います。
今回はMac miniで2WAY・3WAYチャンネルディバイダーを動かすことができました。
あくまで実験用プログラムですので、安全には十分注意し、自己責任でお楽しみください。
ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
ソースコード全文(Mac Channel Divider v0.8)
以下は、Mac mini M4で動作を確認したv0.8の pythonソースコード全文です。なお、こちらで公開用の書き換えは行わず、実際に使用したコードを掲載しています。
Macの「Audio MIDI設定」で作成した「機器セット」で登録した機器が出力対象となります。
(途中表記が変更されている部分がありますが、コードをそのまま上から下までコピーしてテキストファイルに貼り付けて下さい)
※使用は自己責任でお願いします。問題など御座いましたら、ご自身でAIを使い修正などのご対応をお願いします。
ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
"""Mac Channel Divider v0.8 — 2WAY / 3WAY switchable.
Stable v0.7 architecture:
BlackHole 2ch -> one PortAudio input stream -> LR4 crossover
-> ONE macOS Audio MIDI aggregate output stream (4ch for 2WAY, 6ch for 3WAY).
Select devices inside an aggregate by name when Core Audio detection works;
CH-pair selection is provided when it does not. Mode and routes change only
while stopped. Frequency and per-band volume are live-adjustable.
Needs numpy, scipy, sounddevice and tkinter.
Experimental DSP: does not replace physical tweeter / driver protection.
"""
from future import annotations
from collections import deque
import sys
import threading
import tkinter as tk
from tkinter import messagebox, ttk
import numpy as np
import sounddevice as sd
from scipy.signal import butter, sosfilt, sosfilt_zi
SR = 48000
BLOCK = 512
BUFFER_BLOCKS = 32
TARGET_BLOCKS = 5
CROSSFADE_FRAMES = int(SR * 0.08)
MAX_PAIR_COUNT = 32
BANDS = ('low', 'mid', 'high')
BAND_NAMES = {'low': '低音', 'mid': '中音', 'high': '高音'}
def list_audio_devices():
"""Return {numeric device index: PortAudio device dictionary}."""
return {i: device for i, device in enumerate(sd.query_devices())}
def device_label(index, device):
return f"{index}: {device['name']} [入力{device['max_input_channels']} / 出力{device['max_output_channels']}]"
def lr4_filter(freq: int, band: str) -> np.ndarray:
Two cascaded second-order Butterworth sections = LR4 crossover.
biquad = butter(2, freq, btype=band, fs=SR, output='sos')
return np.concatenate((biquad, biquad)).astype(np.float32)
--- Core Audio discovery is ONLY used while stopped to populate the UI. ---
Playback still uses ONE PortAudio output stream (the aggregate device).
We read fullSubDeviceList (UIDs in channel order), activeSubDeviceList,
and each subdevice's output stream configuration. No extra audio threads.
def build_routes_for_subdevices(ordered_devices, reported_channels):
"""Convert [(name, output_ch_count), ...] to [(label, zero_based_pair_start)].
An input-only member contributes 0 output channels. Stereo pairs are kept
within their source device; we never straddle two distinct sound cards.
"""
choices = []
offset = 0
for name, count in ordered_devices:
if count < 0:
raise ValueError('不正なチャンネル数です。')
for i in range(0, count - 1, 2):
start = offset + i
choices.append((f'{name} (CH{start + 1}/{start + 2})', start))
offset += count
if offset != reported_channels:
raise RuntimeError(f'機器セットのCH数が一致しません(Core Audio={offset} / 出力側={reported_channels})。')
if len(choices) < 2:
raise RuntimeError('ステレオ出力2組を検出できませんでした。')
return choices
def mac_aggregate_routes(aggregate_name, reported_channels):
"""Discover aggregate's constituent output devices using macOS Core Audio.
Returns a list of (device+CH label, zero-based channel start). Falls back
safely on failure; does not alter any macOS audio device settings.
"""
if sys.platform != 'darwin':
raise RuntimeError('Core Audioによる機器名の自動取得はmacOS専用です。')
import ctypes as C
import ctypes.util
import struct
def fourcc(text):
return int.from_bytes(text.encode('ascii'), 'big')
class Address(C.Structure):
fields = [('selector', C.c_uint32), ('scope', C.c_uint32),
('element', C.c_uint32)]
class AudioBuffer(C.Structure):
fields = [('channels', C.c_uint32), ('byte_size', C.c_uint32),
('data', C.c_void_p)]
class AudioBufferList(C.Structure):
fields = [('count', C.c_uint32), ('buffers', AudioBuffer * 1)]
ca_path = C.util.find_library('CoreAudio')
cf_path = C.util.find_library('CoreFoundation')
if not ca_path or not cf_path:
raise RuntimeError('Core Audioを読み込めません。')
ca = C.CDLL(ca_path)
cf = C.CDLL(cf_path)
ca.AudioObjectGetPropertyDataSize.argtypes = [
C.c_uint32, C.POINTER(Address), C.c_uint32, C.c_void_p,
C.POINTER(C.c_uint32)]
ca.AudioObjectGetPropertyDataSize.restype = C.c_int32
ca.AudioObjectGetPropertyData.argtypes = [
C.c_uint32, C.POINTER(Address), C.c_uint32, C.c_void_p,
C.POINTER(C.c_uint32), C.c_void_p]
ca.AudioObjectGetPropertyData.restype = C.c_int32
cf.CFStringGetCString.argtypes = [C.c_void_p, C.c_void_p, C.c_long, C.c_uint32]
cf.CFStringGetCString.restype = C.c_bool
cf.CFArrayGetCount.argtypes = [C.c_void_p]
cf.CFArrayGetCount.restype = C.c_long
cf.CFArrayGetValueAtIndex.argtypes = [C.c_void_p, C.c_long]
cf.CFArrayGetValueAtIndex.restype = C.c_void_p
cf.CFRelease.argtypes = [C.c_void_p]
cf.CFRelease.restype = None
glob = fourcc('glob')
outp = fourcc('outp')
def property_data(obj, selector, scope=glob):
addr = Address(fourcc(selector), scope, 0)
size = C.c_uint32(0)
err = ca.AudioObjectGetPropertyDataSize(obj, C.byref(addr), 0, None, C.byref(size))
if err != 0:
raise RuntimeError(f'Core Audioの設定を読み取れません ({selector}: {err})')
if not 0 < size.value <= 1024 * 1024:
raise RuntimeError(f'Core Audioから不正なサイズが返されました ({selector})')
raw = C.create_string_buffer(size.value)
err = ca.AudioObjectGetPropertyData(obj, C.byref(addr), 0, None,
C.byref(size), C.cast(raw, C.c_void_p))
if err != 0:
raise RuntimeError(f'Core Audioの読み取りに失敗しました ({selector}: {err})')
return raw.raw[:size.value]
def ids_for(obj, key):
data = property_data(obj, key)
if len(data) % C.sizeof(C.c_uint32):
raise RuntimeError('Core AudioデバイスIDの形式が不正です。')
return struct.unpack('=' + 'I' * (len(data) // 4), data)
def read_cfstring(ptr):
if not ptr:
raise RuntimeError('空のデバイス名が返されました。')
buffer = C.create_string_buffer(4096)
ok = cf.CFStringGetCString(C.c_void_p(ptr), buffer, len(buffer), 0x08000100)
if not ok:
raise RuntimeError('デバイス名をUTF-8に変換できません。')
return buffer.value.decode('utf-8')
def read_cf_property(obj, selector):
data = property_data(obj, selector)
if len(data) != C.sizeof(C.c_void_p):
raise RuntimeError(f'{selector}の形式が不正です。')
ptr = C.c_void_p.from_buffer_copy(data).value
if not ptr:
raise RuntimeError(f'{selector}が空です。')
return ptr # caller must CFRelease
def device_string(obj, selector):
ptr = read_cf_property(obj, selector)
try:
return read_cfstring(ptr)
finally:
cf.CFRelease(C.c_void_p(ptr))
def output_ch_count(obj):
raw = property_data(obj, 'slay', outp)
if len(raw) < 4:
raise RuntimeError('出力のチャンネル構成が空です。')
count = struct.unpack_from('=I', raw, 0)[0]
if count > 256:
raise RuntimeError('出力ストリーム数が異常です。')
begin = AudioBufferList.buffers.offset
stride = C.sizeof(AudioBuffer)
if len(raw) < begin + count * stride:
raise RuntimeError('出力ストリーム構成が途中で切れています。')
return sum(struct.unpack_from('=I', raw, begin + i * stride)[0]
for i in range(count))
all_ids = ids_for(1, 'dev#') # kAudioObjectSystemObject = 1
matched = []
for device_id in all_ids:
try:
if device_string(device_id, 'lnam') == aggregate_name:
matched.append(device_id)
except RuntimeError:
pass
if len(matched) != 1:
raise RuntimeError(f'「{aggregate_name}」をCore Audioで一意に特定できません({len(matched)}件)。')
aggregate_id = matched[0]
if output_ch_count(aggregate_id) != reported_channels:
raise RuntimeError('Core Audioとsounddeviceの出力CH数が一致しません。')
active_ids = ids_for(aggregate_id, 'agrp')
if not active_ids:
raise RuntimeError('機器セット内に有効なデバイスがありません。')
active_by_uid = {}
for device_id in active_ids:
uid = device_string(device_id, 'uid ')
active_by_uid[uid] = device_id
ptr = read_cf_property(aggregate_id, 'grup') # CFArray of device UID strings
try:
size = cf.CFArrayGetCount(C.c_void_p(ptr))
if not 0 <= size <= 256:
raise RuntimeError('機器セット内の機器数が異常です。')
ordered_uids = [read_cfstring(cf.CFArrayGetValueAtIndex(C.c_void_p(ptr), i))
for i in range(size)]
finally:
cf.CFRelease(C.c_void_p(ptr))
members = []
for uid in ordered_uids:
if uid not in active_by_uid:
continue # disconnected device has no active channels
did = active_by_uid[uid]
members.append((device_string(did, 'lnam'), output_ch_count(did)))
return build_routes_for_subdevices(members, reported_channels)
def design_filters(mode, frequency=1000, low_mid=400, mid_high=3000):
"""Make 4th-order Linkwitz–Riley crossover, stereo SOScascades.
2WAY: low = LR4 LP(f), high = LR4 HP(f) [same v0.7 filters]
3WAY: low = LP(f1); upper = HP(f1),
mid = upper -> LP(f2); high = upper -> HP(f2).
"""
if mode not in ('2WAY', '3WAY'):
raise ValueError('2WAYか3WAYを選んでください。')
if mode == '2WAY':
if not 200 <= int(frequency) <= 5000:
raise ValueError('2WAYの周波数は200~5000 Hzにしてください。')
return {'low': lr4_filter(int(frequency), 'lowpass'),
'high': lr4_filter(int(frequency), 'highpass')}
if not 100 <= int(low_mid) <= 3000:
raise ValueError('低音/中音の周波数は100~3000 Hzにしてください。')
if not 1000 <= int(mid_high) <= 12000:
raise ValueError('中音/高音の周波数は1000~12000 Hzにしてください。')
if int(low_mid) >= int(mid_high):
raise ValueError('低音/中音の周波数を中音/高音より低くしてください。')
upper = lr4_filter(int(low_mid), 'highpass')
return {
'low': lr4_filter(int(low_mid), 'lowpass'),
'mid': np.concatenate([upper, lr4_filter(int(mid_high), 'lowpass')]),
'high': np.concatenate([upper, lr4_filter(int(mid_high), 'highpass')]),
}
class RealtimeEngine:
"""One input + ONE multichannel output stream; v0.7 FIFO is kept."""
def init(self, *, input_device, output_device, output_channels,
mode, routes, frequency, low_mid, mid_high, gains):
self.mode = mode
self.config = (int(frequency), int(low_mid), int(mid_high))
self.sos = design_filters(mode, *self.config)
names = set(self.sos)
if set(routes) != names:
raise ValueError('出力先の設定が2WAY/3WAYと一致しません。')
if len(set(routes.values())) != len(routes):
raise ValueError('各帯域は別々のCHペアに割り当ててください。')
if any(p < 0 or p % 2 for p in routes.values()):
raise ValueError('出力はステレオCHペアを指定してください。')
if not 4 <= output_channels or output_channels < max(routes.values()) + 2:
raise ValueError('機器セットの出力チャンネル数が足りません。')
if mode == '3WAY' and output_channels < 6:
raise ValueError('3WAYには6ch以上の機器セットが必要です。')
if input_device == output_device:
raise ValueError('入力と出力には別々のデバイスを選んでください。')
self.input_device = input_device
self.output_device = output_device
self.output_channels = output_channels
self.routes = dict(routes)
self.gains = {band: float(gains[band]) for band in names}
sd.check_input_settings(device=input_device, channels=2, samplerate=SR,
dtype='float32')
sd.check_output_settings(device=output_device, channels=output_channels,
samplerate=SR, dtype='float32')
self.zi = {band: np.zeros((len(sos), 2, 2), dtype=np.float32)
for band, sos in self.sos.items()}
self._pending_filter = None
self._transition = None
self._lock = threading.Lock()
self._blocks = deque()
self._queued_frames = 0
self._carry = np.empty((0, 2), dtype=np.float32)
self._ready = False
self.active = False
self.input_level = 0.0
self.underflows = 0
self.overflows = 0
self.callback_notes = ''
self._ramp = 0
self.input_stream = None
self.output_stream = Nonedef input_callback(self, indata, frames, time_info, status):
if status:
self.callback_notes = f'入力: {status}'
if not self.active:
return
audio = indata.copy()
self.input_level = float(np.sqrt(np.mean(audio * audio)))
with self._lock:
if len(self._blocks) >= BUFFER_BLOCKS:
old = self._blocks.popleft()
self._queued_frames -= len(old)
self.overflows += 1
self._blocks.append(audio)
self._queued_frames += frames
if self._queued_frames >= TARGET_BLOCKS * BLOCK:
self._ready = True
def _read_input(self, frames):
output = np.zeros((frames, 2), dtype=np.float32)
with self._lock:
if not self._ready:
return output
offset = 0
while offset < frames:
if len(self._carry) == 0:
if not self._blocks:
self.underflows += 1
self._ready = False
break
self._carry = self._blocks.popleft()
self._queued_frames -= len(self._carry)
n = min(frames - offset, len(self._carry))
output[offset:offset + n] = self._carry[:n]
self._carry = self._carry[n:]
offset += n
while self._queued_frames > TARGET_BLOCKS * BLOCK * 3 and self._blocks:
old = self._blocks.popleft()
self._queued_frames -= len(old)
self.overflows += 1
return output
def request_crossover(self, frequency, low_mid, mid_high):
"""Design filters on the Tk thread; audio callback only uses ready SOS."""
config = (int(frequency), int(low_mid), int(mid_high))
filters = design_filters(self.mode, *config)
zi = {name: sosfilt_zi(sos).astype(np.float32)
for name, sos in filters.items()}
self._pending_filter = (config, filters, zi)
def _filter_audio(self, stereo):
if self._transition is None and self._pending_filter is not None:
config, filters, new_zi = self._pending_filter
self._pending_filter = None
first = stereo[0][None, :, None]
init = {band: z[:, None, :] * first for band, z in new_zi.items()}
self._transition = [config, filters, init, 0]
old = {}
for name, sos in self.sos.items():
old[name], self.zi[name] = sosfilt(sos, stereo, axis=0,
zi=self.zi[name])
if self._transition is None:
return old
transition = self._transition
weights = np.clip((transition[3] + np.arange(len(stereo), dtype=np.float32) + 1)
/ CROSSFADE_FRAMES, 0.0, 1.0)[:, None]
result = {}
for name, sos in transition[1].items():
fresh, transition[2][name] = sosfilt(sos, stereo, axis=0,
zi=transition[2][name])
result[name] = old[name] * (1.0 - weights) + fresh * weights
transition[3] += len(stereo)
if transition[3] >= CROSSFADE_FRAMES:
self.config = transition[0]
self.sos = transition[1]
self.zi = transition[2]
self._transition = None
return resultdef output_callback(self, outdata, frames, time_info, status):
outdata.fill(0)
if status:
self.callback_notes = f'出力: {status}'
if not self.active:
return
try:
stereo = self._read_input(frames)
bands = self._filter_audio(stereo)
for name, processed in bands.items():
pair = self.routes[name]
outdata[:, pair:pair + 2] = processed * np.float32(self.gains[name])
if self._ramp < SR // 25:
n = min(frames, SR // 25 - self._ramp)
fade = (self._ramp + np.arange(n, dtype=np.float32)) / (SR // 25)
outdata[:n] *= fade[:, None]
self._ramp += n
np.clip(outdata, -0.85, 0.85, out=outdata)
except Exception as exc:
self.callback_notes = f'DSPエラー: {exc}'
outdata.fill(0)
def start(self):
try:
self.input_stream = sd.InputStream(
device=self.input_device, samplerate=SR, channels=2,
dtype='float32', blocksize=BLOCK, callback=self.input_callback,
latency='high')
self.output_stream = sd.OutputStream(
device=self.output_device, samplerate=SR, channels=self.output_channels,
dtype='float32', blocksize=BLOCK, callback=self.output_callback,
latency='high')
self.active = True
self.input_stream.start()
self.output_stream.start()
except Exception:
self.stop()
raise
def stop(self):
self.active = False
for stream in (self.output_stream, self.input_stream):
if stream is not None:
try:
stream.stop()
except Exception:
pass
try:
stream.close()
except Exception:
pass
self.output_stream = None
self.input_stream = None
class DividerApp:
def init(self, root):
self.root = root
self.engine = None
root.title('Mac Channel Divider v0.8 — 2WAY / 3WAY')
root.geometry('890x760')
root.minsize(780, 690)
self.mode = tk.StringVar(value='2WAY')
self._active_mode = '2WAY'
self._mode_selections = {'2WAY': {'low': 0, 'high': 2},
'3WAY': {'low': 0, 'mid': 2, 'high': 4}}
self.inputs = {}
self.outputs = {}
self.input_name = tk.StringVar()
self.output_name = tk.StringVar()
self.route_vars = {name: tk.StringVar() for name in BANDS}
self.routes_by_label = {}
self.route_hint = tk.StringVar(value='機器セットを検出中…')
self.freq = tk.IntVar(value=1000)
self.low_mid = tk.IntVar(value=400)
self.mid_high = tk.IntVar(value=3000)
self.levels = {name: tk.IntVar(value=5) for name in BANDS}
self.status = tk.StringVar(value='停止中')
self.meter = tk.StringVar(value='入力RMS: --- バッファ不足: --- / 過剰: ---')
ttk.Label(root, text='Mac Channel Divider v0.8',
font=('Helvetica', 19, 'bold')).pack(pady=(12, 3))
ttk.Label(root, text='2WAY / 3WAY切替 | BlackHole → 機器セット → USB DAC',
foreground='#236788').pack(pady=(0, 7))
mode_frame = ttk.Frame(root)
mode_frame.pack(pady=(0, 7))
ttk.Label(mode_frame, text='出力方式: ').pack(side='left', padx=8)
self.mode_buttons = []
for label in ('2WAY', '3WAY'):
button = ttk.Radiobutton(mode_frame, text=label, value=label,
variable=self.mode, command=self.on_mode_changed)
button.pack(side='left', padx=14)
self.mode_buttons.append(button)
devices = ttk.Frame(root)
devices.pack(fill='x', padx=22, pady=(0, 7))
devices.columnconfigure(1, weight=1)
ttk.Label(devices, text='入力(BlackHole)').grid(row=0, column=0, sticky='w', pady=4)
self.input_box = ttk.Combobox(devices, textvariable=self.input_name,
state='readonly')
self.input_box.grid(row=0, column=1, sticky='ew', padx=12)
ttk.Label(devices, text='出力(機器セット)').grid(row=1, column=0, sticky='w', pady=4)
self.output_box = ttk.Combobox(devices, textvariable=self.output_name,
state='readonly')
self.output_box.grid(row=1, column=1, sticky='ew', padx=12)
self.output_box.bind('<<ComboboxSelected>>', self.on_output_selected)
self.scan_button = ttk.Button(devices, text='再検出', command=self.scan_devices)
self.scan_button.grid(row=2, column=1, sticky='e', pady=1)
routing = ttk.LabelFrame(root, text='帯域ごとの出力先(機器セット内)')
routing.pack(fill='x', padx=22, pady=(0, 5))
routing.columnconfigure(1, weight=1)
self.route_boxes = {}
self.route_labels = {}
for row, band in enumerate(BANDS):
label = ttk.Label(routing, text=f'{BAND_NAMES[band]} →')
label.grid(row=row, column=0, sticky='w', padx=(10, 2), pady=4)
combo = ttk.Combobox(routing, state='readonly',
textvariable=self.route_vars[band])
combo.grid(row=row, column=1, sticky='ew', padx=12, pady=4)
self.route_labels[band] = label
self.route_boxes[band] = combo
ttk.Label(routing, textvariable=self.route_hint,
wraplength=770, foreground='#236788').grid(
row=3, column=0, columnspan=2, sticky='w', padx=10, pady=(5, 8))
crossover = ttk.LabelFrame(root, text='クロスオーバー周波数(再生中変更可能)')
crossover.pack(fill='x', padx=22, pady=5)
crossover.columnconfigure(0, weight=1)
self.freq_2way_frame = ttk.Frame(crossover)
self.freq_2way_frame.grid(row=0, column=0, sticky='ew', padx=10)
self.freq_2way_frame.columnconfigure(1, weight=1)
ttk.Label(self.freq_2way_frame, text='低音 / 高音').grid(row=0, column=0, sticky='w')
tk.Scale(self.freq_2way_frame, from_=200, to=5000, resolution=100,
variable=self.freq, orient='horizontal',
command=self.update_frequency).grid(row=0, column=1, sticky='ew')
self.freq_3way_frame = ttk.Frame(crossover)
self.freq_3way_frame.grid(row=0, column=0, sticky='ew', padx=10)
self.freq_3way_frame.columnconfigure(1, weight=1)
ttk.Label(self.freq_3way_frame, text='低音 / 中音').grid(row=0, column=0, sticky='w')
tk.Scale(self.freq_3way_frame, from_=100, to=3000, resolution=100,
variable=self.low_mid, orient='horizontal',
command=self.update_frequency).grid(row=0, column=1, sticky='ew')
ttk.Label(self.freq_3way_frame, text='中音 / 高音').grid(row=1, column=0, sticky='w')
tk.Scale(self.freq_3way_frame, from_=1000, to=12000, resolution=100,
variable=self.mid_high, orient='horizontal',
command=self.update_frequency).grid(row=1, column=1, sticky='ew')
gains = ttk.LabelFrame(root, text='出力音量(%) / 再生中変更可能')
gains.pack(fill='x', padx=22, pady=5)
gains.columnconfigure(1, weight=1)
self.gain_labels = {}
self.gain_scales = {}
for row, band in enumerate(BANDS):
label = ttk.Label(gains, text=BAND_NAMES[band])
label.grid(row=row, column=0, sticky='w', padx=(10, 0))
scale = tk.Scale(gains, from_=0, to=30, resolution=1,
variable=self.levels[band], orient='horizontal',
command=self.update_levels)
scale.grid(row=row, column=1, sticky='ew', padx=8)
self.gain_labels[band] = label
self.gain_scales[band] = scale
actions = ttk.Frame(root)
actions.pack(pady=7)
self.start_button = ttk.Button(actions, text='▶ 再生開始', command=self.start)
self.start_button.pack(side='left', padx=10)
self.stop_button = ttk.Button(actions, text='■ 停止', command=self.stop,
state='disabled')
self.stop_button.pack(side='left', padx=10)
ttk.Label(root, textvariable=self.status, foreground='#236788',
wraplength=820).pack(pady=3)
ttk.Label(root, textvariable=self.meter).pack(pady=3)
ttk.Label(root, text='※ 3WAYは6ch以上の機器セットが必要です。'
'ツイーターはDSPだけで保護できません。',
foreground='#aa4a1e').pack(pady=3)
self.on_mode_changed()
self.scan_devices()
root.protocol('WM_DELETE_WINDOW', self.close)
root.after(250, self.refresh_meter)def save_mode_routes(self):
stored = self._mode_selections[self._active_mode]
for name in stored:
label = self.route_vars[name].get()
if label in self.routes_by_label:
stored[name] = self.routes_by_label[label]
def fill_mode_routes(self):
"""Use each mode's last selected CH pairs; never auto-duplicate pairs."""
by_start = {start: label for label, start in self.routes_by_label.items()}
used = set()
labels = list(self.routes_by_label)
for band in (('low', 'high') if self.mode.get() == '2WAY' else BANDS):
preferred = self._mode_selections[self.mode.get()].get(band)
candidate = by_start.get(preferred)
if candidate is None or candidate in used:
candidate = next((lab for lab in labels if lab not in used), '')
self.route_vars[band].set(candidate)
if candidate:
used.add(candidate)
def on_mode_changed(self):
if self.engine is not None:
self.mode.set(self._active_mode)
return
self.save_mode_routes()
self._active_mode = self.mode.get()
if self.mode.get() == '2WAY':
self.route_labels['mid'].grid_remove()
self.route_boxes['mid'].grid_remove()
self.freq_3way_frame.grid_remove()
self.freq_2way_frame.grid()
self.gain_labels['mid'].grid_remove()
self.gain_scales['mid'].grid_remove()
else:
self.route_labels['mid'].grid()
self.route_boxes['mid'].grid()
self.freq_2way_frame.grid_remove()
self.freq_3way_frame.grid()
self.gain_labels['mid'].grid()
self.gain_scales['mid'].grid()
self.fill_mode_routes()
self.refresh_route_hint()
def refresh_route_hint(self):
count = len(self.routes_by_label)
if self.mode.get() == '3WAY' and count < 3:
self.route_hint.set('3WAYにはステレオ出力3組(合計6ch以上)が必要です。'
'3台のDACを含む機器セットを選択してください。')
elif not self.routes_by_label:
self.route_hint.set('機器セットを選んでください。')
elif getattr(self, '_discovery_warning', ''):
self.route_hint.set('CH番号で手動選択してください(機器名を取得できませんでした)。理由: '
+ self._discovery_warning)
else:
self.route_hint.set('Core Audioで取得した機器名とCH番号から出力先を選べます。'
'割り当て変更は停止中に行います。')
def scan_devices(self):
if self.engine is not None:
return
previous_in = self.inputs.get(self.input_name.get())
previous_out = self.outputs.get(self.output_name.get())
try:
devices = list_audio_devices()
self.inputs = {device_label(i, d): i for i, d in devices.items()
if d['max_input_channels'] >= 2}
self.outputs = {device_label(i, d): i for i, d in devices.items()
if d['max_output_channels'] >= 4}
except Exception as exc:
messagebox.showerror('デバイス検出エラー', str(exc))
return
self.input_box['values'] = list(self.inputs)
self.output_box['values'] = list(self.outputs)
if self.inputs:
selected = next((lab for lab, idx in self.inputs.items() if idx == previous_in), None)
if selected is None:
selected = next((lab for lab in self.inputs if 'BlackHole 2ch' in lab), None)
self.input_name.set(selected or next(iter(self.inputs)))
else:
self.input_name.set('')
if self.outputs:
selected = next((lab for lab, idx in self.outputs.items() if idx == previous_out), None)
if selected is None:
selected = next((lab for lab in self.outputs if '機器セット' in lab), None)
self.output_name.set(selected or next(iter(self.outputs)))
else:
self.output_name.set('')
self.on_output_selected()
def on_output_selected(self, _=None):
if self.engine is not None:
return
self.save_mode_routes()
label = self.output_name.get()
if label not in self.outputs:
self.routes_by_label = {}
for combo in self.route_boxes.values():
combo['values'] = []
self.fill_mode_routes()
self.refresh_route_hint()
return
device = sd.query_devices(self.outputs[label])
count = int(device['max_output_channels'])
try:
choices = mac_aggregate_routes(str(device['name']), count)
self._discovery_warning = ''
except Exception as exc:
choices = [(f'CH{i * 2 + 1}/{i * 2 + 2}(手動)', i * 2)
for i in range(min(MAX_PAIR_COUNT, count // 2))]
self._discovery_warning = str(exc)
self.routes_by_label = dict(choices)
for combo in self.route_boxes.values():
combo['values'] = list(self.routes_by_label)
self.fill_mode_routes()
self.refresh_route_hint()
def update_frequency(self, _=None):
if self.engine is not None:
try:
self.engine.request_crossover(self.freq.get(),
self.low_mid.get(), self.mid_high.get())
self.status.set(f'再生中:周波数変更中({self.mode.get()})')
except ValueError as exc:
self.status.set('設定エラー: ' + str(exc))
def update_levels(self, _=None):
if self.engine is not None:
for band in self.engine.gains:
self.engine.gains[band] = self.levels[band].get() / 100.0
def start(self):
if self.engine is not None:
return
try:
if self.input_name.get() not in self.inputs or self.output_name.get() not in self.outputs:
raise ValueError('BlackHole入力と機器セットを選んでください。')
mode = self.mode.get()
required = ('low', 'high') if mode == '2WAY' else BANDS
if any(self.route_vars[band].get() not in self.routes_by_label
for band in required):
raise ValueError('必要な帯域の出力先を指定してください。')
routes = {band: self.routes_by_label[self.route_vars[band].get()]
for band in required}
if len(set(routes.values())) != len(required):
raise ValueError('各帯域に異なるDAC(CHペア)を選んでください。')
output_device = self.outputs[self.output_name.get()]
reported = int(sd.query_devices(output_device)['max_output_channels'])
if mode == '3WAY' and reported < 6:
raise ValueError('3WAYには6ch以上の機器セットが必要です。')
output_channels = max(routes.values()) + 2
# Validate UI frequencies before opening any audio streams.
design_filters(mode, self.freq.get(), self.low_mid.get(), self.mid_high.get())
engine = RealtimeEngine(
input_device=self.inputs[self.input_name.get()],
output_device=output_device, output_channels=output_channels,
mode=mode, routes=routes, frequency=self.freq.get(),
low_mid=self.low_mid.get(), mid_high=self.mid_high.get(),
gains={band: self.levels[band].get() / 100 for band in required})
engine.start()
self.engine = engine
self.start_button.configure(state='disabled')
self.stop_button.configure(state='normal')
self.input_box.configure(state='disabled')
self.output_box.configure(state='disabled')
for combo in self.route_boxes.values():
combo.configure(state='disabled')
self.scan_button.configure(state='disabled')
for button in self.mode_buttons:
button.configure(state='disabled')
self.status.set(f'再生中:{mode} | ' + ' / '.join(
f'{BAND_NAMES[band]} → {self.route_vars[band].get()}' for band in required))
except Exception as exc:
messagebox.showerror('起動エラー', str(exc))
self.status.set('開始できませんでした。設定と48kHzを確認してください。')
def stop(self):
if self.engine is not None:
self.engine.stop()
self.engine = None
self.start_button.configure(state='normal')
self.stop_button.configure(state='disabled')
self.input_box.configure(state='readonly')
self.output_box.configure(state='readonly')
for combo in self.route_boxes.values():
combo.configure(state='readonly')
self.scan_button.configure(state='normal')
for button in self.mode_buttons:
button.configure(state='normal')
self.status.set('停止中')
self.meter.set('入力RMS: --- バッファ不足: --- / 過剰: ---')
def refresh_meter(self):
if self.engine is not None:
e = self.engine
self.meter.set(f'入力RMS: {e.input_level:.5f} | '
f'バッファ不足: {e.underflows} / 過剰: {e.overflows}')
if e.callback_notes:
self.status.set('音声デバイス通知: ' + e.callback_notes[:120])
self.root.after(250, self.refresh_meter)
def close(self):
if self.engine is not None:
self.engine.stop()
self.root.destroy()
if name == 'main':
root = tk.Tk()
DividerApp(root)
root.mainloop()