Beispiel #1
0
def choose_device():
    devices = miniaudio.Devices()
    print("Available playback devices:")
    playbacks = devices.get_playbacks()
    for d in enumerate(playbacks, 1):
        print("{num} = {name}".format(num=d[0], name=d[1]['name']))
    choice = int(input("play on which device? "))
    return playbacks[choice-1]
Beispiel #2
0
def choose_devices():
    devices = miniaudio.Devices(backends=backends)
    print("Available capture devices:")
    captures = devices.get_captures()
    for d in enumerate(captures, 1):
        print("{num} = {name}".format(num=d[0], name=d[1]['name']))
    capture_choice = int(input("record from which device? "))
    print("\nAvailable playback devices:")
    playbacks = devices.get_playbacks()
    for d in enumerate(playbacks, 1):
        print("{num} = {name}".format(num=d[0], name=d[1]['name']))
    playback_choice = int(input("play on which device? "))
    return captures[capture_choice-1], playbacks[playback_choice-1]
Beispiel #3
0
 def ma_query_device_details(self, device: Optional[Union[int, str]] = None, kind: Optional[str] = None) -> Any:
     devices = miniaudio.Devices()
     if kind == miniaudio.DeviceType.PLAYBACK:
         devs = devices.get_playbacks()
     elif kind == miniaudio.DeviceType.CAPTURE:
         devs = devices.get_playbacks()
     else:
         devs = devices.get_playbacks() + devices.get_captures()
     id_buf = miniaudio.ffi.buffer(device)
     for d in devs:
         if miniaudio.ffi.buffer(d["id"]) == id_buf:
             return d
     raise LookupError("device not found")
    def _run(self):
        devices = miniaudio.Devices()
        captures = devices.get_captures()
        selected_device = captures[self._device_id]
        capture = \
            miniaudio.CaptureDevice(buffersize_msec=1000,
                                    sample_rate=44100,
                                    device_id=selected_device["id"])

        recorder = self.__stream_loop()
        next(recorder)

        while True:
            message = self.message_queue.get()
            if message is None:
                continue
            if message.type == MessageType.START:
                if self._state == "START":
                    print("Audio streaming has already started")
                else:
                    self._stream_data = []
                    capture.start(recorder)
                    self._record = True
                    self._state = "START"
            elif message.type == MessageType.STOP:
                if self._state == "STOP":
                    print("Audio streaming has already stopped")
                else:
                    capture.stop()
                    self._record = False
                    file_name = \
                        "{0}/{1}-{2}-{3}.wav".format(self.output_path,
                                                    self.name,
                                                    message.experiment_id,
                                                    str(message.stimulus_id).zfill(2))
                    self._save_to_file(file_name, capture)
                    self._state = "STOP"
            elif message.type == MessageType.TERMINATE:
                self._terminate = True
                break
Beispiel #5
0
def main(config: str, make_config: bool) -> None:
    """
    This is a module which implements realtime polyphonic FM synthesis in Python
    controllable by MIDI. Note that this is very CPU-intensive.

    It's got the following features:

    - configurable polyphony;

    - AD envelope (no sustain yet);

    - dispatches MIDI IN events like NOTE_ON and NOTE_OFF events to the synthesizer.

    To use this yourself, you will need:

    - a MIDI IN port, can be virtual (I'm using IAC in Audio MIDI Setup on macOS);

    - an AUDIO OUT, can be virtual (I'm using BlackHole on macOS);

    - a DAW project which will be configured as follows (Renoise as an example):

        - a MIDI Instrument in the DAW configured to output notes to the MIDI port that
          fmsynth listens on (I call my virtual MIDI port "IAC fmsynth");

        - a #Line Input routing in the DAW configured to catch audio from the out that
          fmsynth (like "BlackHole 16ch 1+2");

        - turn on "MIDI Return Mode" to compensate latency;

        - in Ableton Live use "External Instrument" to do this in one place and
          automatically compensate latency.

    You can customize the ports by creating a config file.  Use `--make-config` to
    output a new config to stdout.

    Then run `python -m aiotone.fmsynth --config=PATH_TO_YOUR_CONFIG_FILE`.
    """
    if make_config:
        with open(CURRENT_DIR / "aiotone-fmsynth.ini") as f:
            print(f.read())
        return

    cfg = configparser.ConfigParser()
    cfg.read(config)

    devices = miniaudio.Devices()
    playbacks = devices.get_playbacks()
    audio_out = cfg["audio-out"]["out-name"]
    sample_rate = cfg["audio-out"].getint("sample-rate")
    buffer_msec = cfg["audio-out"].getint("buffer-msec")
    polyphony = cfg["audio-out"].getint("polyphony")
    for playback in playbacks:
        if playback["name"] == audio_out:
            play_id = playback["id"]
            break
    else:
        raise click.UsageError(f"No audio out available called {audio_out}")

    with miniaudio.PlaybackDevice(
        device_id=play_id,
        nchannels=2,
        sample_rate=sample_rate,
        output_format=miniaudio.SampleFormat.SIGNED16,
        buffersize_msec=buffer_msec,
    ) as dev:
        synth = Synthesizer(sample_rate=sample_rate, polyphony=polyphony)
        stream = synth.stereo_out()
        init(stream)
        dev.start(stream)
        try:
            asyncio.run(async_main(synth, cfg["midi-in"]))
        except KeyboardInterrupt:
            pass
Beispiel #6
0
def test_devices():
    devs = miniaudio.Devices()
    devs.get_playbacks()
    devs.get_captures()
Beispiel #7
0
"""
List the available audio devices.
"""

import miniaudio

devices = miniaudio.Devices(backends=[])
print("Backend: {}".format(devices.backend))

out_devices = devices.get_playbacks()
print("\nPlayback Devices:")
for device in out_devices:
    print(device)

in_devices = devices.get_captures()
print("\nCapture Devices:")
for device in in_devices:
    print(device)
Beispiel #8
0
 def ma_query_devices(self) -> List[Dict[str, Any]]:
     devices = miniaudio.Devices()
     playback, record = devices.get_playbacks(), devices.get_captures()
     return playback + record
Beispiel #9
0
 def ma_query_apis(self) -> List[Dict[str, Any]]:
     backend = miniaudio.Devices().backend
     return [{
         'name': backend
     }]