bastibe / SoundCard

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

record random length voice #40

Closed kunaia closed 5 years ago

kunaia commented 5 years ago

can you show us an example how to record voice with soundcard.default_microrphone().recorder()? I am trying to start recording when I press, let's say 's' key on keyboard and stop recording when I press 'e'.

bastibe commented 5 years ago

That really depends on your actual use case. Just call Recorder.record() repeatedly until you press your key. There is no magic to it.

with soundcard.default_microphone().recorder() as rec:
    while True:
        data = rec.record()
        if key_has_been_pressed():
            break
kunaia commented 5 years ago

yes, I have solved that problem, but sometimes it shows the following problem: Assertion 's' failed at pulse/stream.c:1411, function pa_stream_connect_record(). Aborting.

why?

my code here:

sounds = []
while True:
    sounds.clear()
    with rec.recorder(samplerate=48000) as mic:
        while keyboard.is_pressed('r'):
            sound = mic.record()
            sounds.append(sound)
bastibe commented 5 years ago

Please post a complete, executable example, and a complete stack trace.

kunaia commented 5 years ago
import os
import numpy as np
import soundcard as snd
import keyboard as kbrd
from scipy.io.wavfile import write

rec = snd.default_microphone()
spk = snd.default_speaker()

cnt = 1
sounds = []
while True:
    sounds.clear()
    with rec.recorder(samplerate=48000) as mic:
        while kbrd.is_pressed('r'):
            sound = mic.record()
            sounds.append(sound)

    if len(sounds) > 0:
        voice = sounds[0]
        for i in range(1, len(sounds)):
            voice = np.append(voice, sounds[i], axis=0)

        voice = np.int16(voice / np.max(np.abs(voice)) * 32767)
        write('{}.wav'.format(cnt), 48000, voice)

        print('\n')
        cnt += 1