Microphone recording in 2022.1.2 for an undefined amount of time


I would like to record sound, for for an undefined amount of time / arbitrary amount.
I use the second example for psychopy 2022.1.2 here

Here is my minimal example:

import psychopy

# does not change anything....
# from psychopy import prefs
# prefs.hardware['audioLib'] = ['PTB']

import psychopy.core as core
import psychopy.visual as visual
#import psychopy.sound.Microphone as Microphone  # does not work.
import psychopy.sound.microphone as Microphone


win = visual.Window([400,400])

mic = Microphone(bufferSecs=2.0)
mic.start()  # start recording

# main trial drawing loop
win.flip()  # calling the window flip function

mic.stop()  # stop recording
audioClip = mic.getRecording()

Ive tried to import the microphone as started in the example:

import psychopy.sound.Microphone as Microphone

but that does not work.

Ive also tried changing it to microphone, with small, which does import a microphone but it’s unable to use the argument bufferSecs.

changing the preference sound device does not change anything.

This is the output:

Traceback (most recent call last):
  File "microphone_check.py", line 23, in <module>
    mic = Microphone(bufferSecs=2.0)
TypeError: 'module' object is not callable
0.6358 	WARNING 	Speech-to-text recognition using Google online services is not available (use command `pip install google-api-core google-auth google-cloud google-cloud-speech googleapis-common-protos` to get it). Transcription will be unavailable using that service this session.
2.3805 	WARNING 	Monitor specification not found. Creating a temporary one...

Process finished with exit code 1

I found a solution using sounddevice rather than psychopy

Similar to this example

switching to sounddevice i.e. import sounddevice as sd rather than psychopy.sound.microphone is what can work for now.

Below example is tested on psychopy 2022.1.2 on windows 10. with a logitech HD pro webcam C920 as the Microphone and playing the sound using VLC media player.

The below code (adapted to a psychopy “experiment” from this example) opens a sound device and streams to it for an undefined amount of time (until 4 trials are completed),
The experiment is just clicking n 4 times.
I did have to go into windows settings to change microphone to the correct one. (and keeping device = None)

#!/usr/bin/env python3
import os
import queue
import sys

import sounddevice as sd
import soundfile as sf
from psychopy import core, event, visual

win = visual.Window([1200,400], monitor="testMonitor", units="deg")
textStim = visual.TextStim(win,height=1,text="Start text")

trials = 4
q = queue.Queue()

channels = 1

print("list of sound devices found")
print("setting devices to none should work.. ")
print("tested in windows:  Make sure your microphone is connected to your PC.Select Start > Settings > System > "
      "Sound.In Sound settings, go to Input and in the Choose your input device list, select the microphone or recording device you want to use...."
      " make sure you can see that it is recording some sound (windows 10)")

device = None
if os.path.exists(filename):os.remove(filename)

list_devices = False
samplerate = 44100
subtype = None

def callback(indata, frames, time, status):
    """This is called (from a separate thread) for each audio block."""
    if status:
        print(status, file=sys.stderr)

file =  sf.SoundFile(filename, mode='x', samplerate=samplerate,
                  channels=channels, subtype=subtype)

with sd.InputStream(samplerate=samplerate, device=device,
                        channels=channels, callback=callback):

    for trial in range(trials):

        textStim.setText("Trial %s\npress n for next trial"% str(trial))

        nextTrial = False
        while not nextTrial:
            response = event.getKeys(["n","escape"])
            if response:
                if response[0] == "n":
                    nextTrial = True
                elif response[0] == "escape":
                    print("escape was hit - stopping trials")
                    print("wav file saved in %s" % os.getcwd() + "/" + filename)

print("wav file saved in %s" % os.getcwd() + "/" + filename)
print("VLC media player worked for me for playing the recording... Groove Music did not... :/ ")

textStim.setText("wav file saved in %s" % os.getcwd() + "\n\n and is named:\n%s"% filename )

psychopy.sound.microphone is the module containing the microphone class, what you want is psychopy.sound.microphone.Microphone