Python Forum

Full Version: PyAudio [Errorno -9999] Unanticipated Host Error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I hope everyone is doing well. I have been using pyaudio for quite some time now, however, recently it stopped working and throwing me an OSERROR, I don't specifically remember changing anything. The relevant part of the script is reproduced below for testing purpose along with the error that I am receiving.

Any help will be greatly appreciated.

import pyaudio
import wave
import threading
import struct


# Monkey patch wave library
def _new_read_fmt_chunk(self, chunk):    
    WAVE_FORMAT_EXTENSIBLE = 65534
    WAVE_FORMAT_PCM = 0x0001
    try:
        wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack_from('<HHLLH',
                                                                                                         chunk.read(14))
    except struct.error:
        raise EOFError from None
    if wFormatTag == WAVE_FORMAT_PCM or wFormatTag == WAVE_FORMAT_EXTENSIBLE:
        try:
            sampwidth = struct.unpack_from('<H', chunk.read(2))[0]
        except struct.error:
            raise EOFError from None
        self._sampwidth = (sampwidth + 7) // 8
        if not self._sampwidth:
            raise Error('bad sample width')
    else:
        raise Error('unknown format: %r' % (wFormatTag,))
    if not self._nchannels:
        raise Error('bad # of channels')
    self._framesize = self._nchannels * self._sampwidth
    self._comptype = 'NONE'
    self._compname = 'not compressed'
wave.Wave_read._read_fmt_chunk = _new_read_fmt_chunk


class BackGroundMusic:
    def __init__(self):
        self.p = pyaudio.PyAudio()
        self.enabled = False

    def __del__(self):
        self.p.terminate()

    def play(self, bgm_file):
        if bgm_file[-4:].lower() != '.wav':
            return
        self.enabled = True
        threading.Thread(target=self.background_thread, args=(bgm_file, )).start()

    def background_thread(self, bgm_file):
        chunk = 1024
        with wave.open(bgm_file, 'rb') as wf:
            stream = self.p.open(format=self.p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(),
                                 rate=wf.getframerate(), output=True)
            while self.enabled:
                data = wf.readframes(chunk)
                if not data:
                    wf.rewind()
                stream.write(data)
            stream.close()

    def stop(self):
        self.enabled = False


x = BackGroundMusic()
bgm_file = r'C:\file_path\music_file.wav'
x.play(bgm_file)
Error:
Exception in thread Thread-1: Traceback (most recent call last): File "C:\Program Files (x86)\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Program Files (x86)\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:/Users/xxxx/PycharmProjects/hm_API/hm_API/music/__init__.py", line 50, in background_thread stream = self.p.open(format=self.p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), File "C:\Users\xxxx\AppData\Roaming\Python\Python38\site-packages\pyaudio.py", line 750, in open stream = Stream(self, *args, **kwargs) File "C:\Users\xxxx\AppData\Roaming\Python\Python38\site-packages\pyaudio.py", line 441, in __init__ self._stream = pa.open(**arguments) OSError: [Errno -9999] Unanticipated host error
Note: The wave file is sampled at 96Khz.
Took your code, only change I made was the name of the file, and it played just fine. I'd do the usuals - reboot, make sure the file plays in a different player.
Thank you for the response. however, unfortunately rebooting, using a different file etc doesn't solve the problem, i have tried by reinstalling pyaudio too but the error still persists
Looking around, I have found the following possibilities:
Unsupported bit rate (make sure you try files in different and common bit rates, like 44.1K and 48K)
Microphone privacy settings - enable and disable and see if makes a difference (even though you are not using, several people have reported this to cause the error)

Make sure your settings are supported.
import pyaudio
soundObj = pyaudio.PyAudio()

# Learn what your OS+Hardware can do
defaultCapability = soundObj.get_default_host_api_info()
print defaultCapability

# See if you can make it do what you want
isSupported = soundObj.is_format_supported(input_format=pyaudio.paInt8, input_channels=1, rate=22050, input_device=0)
print isSupported
Credit where it is due, I got that from Stack Overflow
Thank you for the help, however unfortunately, following your advice did not resolve the issue. I believe something has gotten messed up in my portaudio binary. I tried removing and reinstalling it but still no dice. Can someone recommend a simpler sound library with synthesizer support?. The library that does not implement threading on its own will be recommended.
pygame has audio support. The following will play an mp3 file. It will also play midi notes.
import pygame.mixer

pygame.mixer.init()
pygame.mixer.music.load('V.mp3')
pygame.mixer.music.play(0)