1 year ago

#268638

test-img

Joseph Yu

OSError: [Errno -9999] Unanticipated host error --- PaMacCore (AUHAL)|| AUHAL component not found

I'm trying to use PyAudio to record. I'm on a 2021 MacBook Pro (Apple Silicon) with MacOS Monterey 12.2.1, Python 3.9.10. However, when I try to run the following code (taken from this discussion: https://stackoverflow.com/a/6743593/18138581) I get the error below (Please note that the error stems from the "record" function). I have made sure that Terminal has access to the microphone and I tried installing portaudio with homebrew as some have suggested. However, none of it has worked. Does anyone have any clue how I could solve this? Thanks in advance.

from sys import byteorder
from array import array
from struct import pack

import pyaudio
import wave

THRESHOLD = 500
CHUNK_SIZE = 1024
FORMAT = pyaudio.paInt16
RATE = 44100

def is_silent(snd_data):
    "Returns 'True' if below the 'silent' threshold"
    return max(snd_data) < THRESHOLD

def normalize(snd_data):
    "Average the volume out"
    MAXIMUM = 16384
    times = float(MAXIMUM)/max(abs(i) for i in snd_data)

    r = array('h')
    for i in snd_data:
        r.append(int(i*times))
    return r

def trim(snd_data):
    "Trim the blank spots at the start and end"
    def _trim(snd_data):
        snd_started = False
        r = array('h')

        for i in snd_data:
            if not snd_started and abs(i)>THRESHOLD:
                snd_started = True
                r.append(i)

            elif snd_started:
                r.append(i)
        return r

    # Trim to the left
    snd_data = _trim(snd_data)

    # Trim to the right
    snd_data.reverse()
    snd_data = _trim(snd_data)
    snd_data.reverse()
    return snd_data

def add_silence(snd_data, seconds):
    "Add silence to the start and end of 'snd_data' of length 'seconds' (float)"
    silence = [0] * int(seconds * RATE)
    r = array('h', silence)
    r.extend(snd_data)
    r.extend(silence)
    return r

def record():
    """
    Record a word or words from the microphone and 
    return the data as an array of signed shorts.

    Normalizes the audio, trims silence from the 
    start and end, and pads with 0.5 seconds of 
    blank sound to make sure VLC et al can play 
    it without getting chopped off.
    """
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=1, rate=RATE,
        input=True, output=True,
        frames_per_buffer=CHUNK_SIZE)

    num_silent = 0
    snd_started = False

    r = array('h')

    while 1:
        # little endian, signed short
        snd_data = array('h', stream.read(CHUNK_SIZE))
        if byteorder == 'big':
            snd_data.byteswap()
        r.extend(snd_data)

        silent = is_silent(snd_data)

        if silent and snd_started:
            num_silent += 1
        elif not silent and not snd_started:
            snd_started = True

        if snd_started and num_silent > 30:
            break

    sample_width = p.get_sample_size(FORMAT)
    stream.stop_stream()
    stream.close()
    p.terminate()

    r = normalize(r)
    r = trim(r)
    r = add_silence(r, 0.5)
    return sample_width, r

def record_to_file(path):
    "Records from the microphone and outputs the resulting data to 'path'"
    sample_width, data = record()
    data = pack('<' + ('h'*len(data)), *data)

    wf = wave.open(path, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(sample_width)
    wf.setframerate(RATE)
    wf.writeframes(data)
    wf.close()

if __name__ == '__main__':
    print("please speak a word into the microphone")
    record_to_file('demo.wav')
    print("done - result written to demo.wav")

Output:

please speak a word into the microphone
||PaMacCore (AUHAL)|| AUHAL component not found.
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
Input In [3], in <cell line: 118>()
    118 if __name__ == '__main__':
    119     print("please speak a word into the microphone")
--> 120     record_to_file('demo.wav')
    121     print("done - result written to demo.wav")

Input In [3], in record_to_file(path)
    106 def record_to_file(path):
    107     "Records from the microphone and outputs the resulting data to 'path'"
--> 108     sample_width, data = record()
    109     data = pack('<' + ('h'*len(data)), *data)
    111     wf = wave.open(path, 'wb')

Input In [3], in record()
     60 """
     61 Record a word or words from the microphone and 
     62 return the data as an array of signed shorts.
   (...)
     67 it without getting chopped off.
     68 """
     69 p = pyaudio.PyAudio()
---> 70 stream = p.open(format=FORMAT, channels=1, rate=RATE,
     71     input=True, output=True,
     72     frames_per_buffer=CHUNK_SIZE)
     74 num_silent = 0
     75 snd_started = False

File ~/miniforge3/envs/tfenv/lib/python3.9/site-packages/pyaudio.py:750, in PyAudio.open(self, *args, **kwargs)
    742 def open(self, *args, **kwargs):
    743     """
    744     Open a new stream. See constructor for
    745     :py:func:`Stream.__init__` for parameter details.
    746 
    747     :returns: A new :py:class:`Stream`
    748     """
--> 750     stream = Stream(self, *args, **kwargs)
    751     self._streams.add(stream)
    752     return stream

File ~/miniforge3/envs/tfenv/lib/python3.9/site-packages/pyaudio.py:441, in Stream.__init__(self, PA_manager, rate, channels, format, input, output, input_device_index, output_device_index, frames_per_buffer, start, input_host_api_specific_stream_info, output_host_api_specific_stream_info, stream_callback)
    438     arguments['stream_callback'] = stream_callback
    440 # calling pa.open returns a stream object
--> 441 self._stream = pa.open(**arguments)
    443 self._input_latency = self._stream.inputLatency
    444 self._output_latency = self._stream.outputLatency

OSError: [Errno -9999] Unanticipated host error

python

audio-recording

pyaudio

microphone

portaudio

0 Answers

Your Answer

Accepted video resources