bastibe / SoundCard

A Pure-Python Real-Time Audio Library
https://soundcard.readthedocs.io
BSD 3-Clause "New" or "Revised" License
680 stars 69 forks source link

added co routine for tutorial for better real time experience #58

Closed gaslitbytech closed 5 years ago

gaslitbytech commented 5 years ago

I just wanted to share this as it me as it helped me as a first time user get a better real time feedback. Though I'm new to asyncio and couldn't find a better solution then having the await asyncio.sleep(0.0000001) which doesn't seem to be ideal.

Unfortunately it is new asyncio python 3.7 only as well.

gaslitbytech commented 5 years ago

This was just a idea and I should do more work before submitting this.

bastibe commented 5 years ago

I like it! If you add a bit of explanation, I'd be happy to merge it!

gaslitbytech commented 5 years ago

I just attempted to try to finish this though now with the same code sample I get

ValueError: all the input arrays must have same number of dimensions

Full snippet

    import soundcard as sc

    import asyncio
    import numpy

    default_mic = sc.default_microphone()
    default_speaker = sc.default_speaker()

    # buffer for the data
    data = []

    # task to continuously record
    async def record_mic(selected_mic, buffer):
        with selected_mic.recorder(samplerate=48*1000) as mic:
            while True:
                buffer.append(mic.record(numframes=1024))
                await asyncio.sleep(0.0000001)

    # task to continuously play
    async def play_speaker(selected_speaker, buffer):
        with selected_speaker.player(samplerate=48*1000) as sp:
            while True:
                sp.play(data.pop())
                await asyncio.sleep(0.0000001)

    # main entry point
    async def main():
        await asyncio.gather(
            record_mic(default_mic, data),
            play_speaker(default_speaker, data)
        )

    asyncio.run(main())

pip dependencies

cffi==1.12.3
numpy==1.16.4
pycparser==2.19
SoundCard==0.3.2