PyAudio Stream causes Windows Heap Corruption (-1073740940 (0xC0000374)) when reading from stream

I’ve been having issues with PyAudio’s Stream when trying to read it.

It crashes with exit code -1073740940 which is a Windows Heap Corruption error 0xC0000374. It happens during the line where I read from the PyAudio stream like so: stream.read(chunk_size).

I have also seen it crash with -1073741819 ACCESS_VIOLATION_EXCEPTION but I cannot replicate that.

Here are two videos of me trying to spam the record key to invoke the crash:

  • Without Error (silent crash): https://imgur.com/VQqbbBR
  • With Error: https://imgur.com/Bg5r07I

No, it does not only happen when I spam it. It happens randomly, but it increases the chances of crashing when I spam it. Sometimes at the first few tries, and sometimes over a 100 tries.

I have tried using solutions from this stackoverflow question to no avail

Here is the code if anyone would like to replicate this:

Permanent Pastebin Link (https://pastebin.com/uDeBtGgv)

# pip install wave keyboard requests pyaudio sounddevice

import sys
import traceback
import wave
from pathlib import Path
from time import sleep
import keyboard
import requests
import pyaudio
import sounddevice as sd
from threading import Thread
import faulthandler

BASE_DIR = Path(__file__).resolve().parent
sys.path.append(str(BASE_DIR))

# The key to record audio with
MIC_RECORD_KEY = "prtscn"
CANCEL_REQUEST_KEY = "delete"

def find_device_index(query: callable):
    query_results = list(
        filter(
            query,
            list(sd.query_devices())
            )
    )

    if not len(query_results): return None
    else: return query_results[0]['index']

# Change this to your mic name first for this to work.
MIC = find_device_index( lambda x: x['max_output_channels'] == 0 and x['name'] == 'Jack Mic (Realtek(R) Audio)' )

''' Functions '''
    

def on_press_key(_=None):

    try:
        global frames, recording, stream

        if recording: return

        print('Listening...')

        print('Recording has started.')

        frames = []
        recording = True
        stream = p.open(format=FORMAT,
                        channels=MIC_CHANNELS,
                        rate=MIC_SAMPLING_RATE,
                        input=True,
                        frames_per_buffer=CHUNK,
                        input_device_index=MIC,)
        print('opened stream')

        return print('finished press key process')
            
    except: traceback.print_exc()


def on_release_key(_=None):
    try:
        print('Stopped listening.')
        global recording, stream
        recording = False
        stream.stop_stream()
        stream.close()
        stream = None

        # if key not held down for long enough
        if not frames or len(frames) < 20:
            print('No audio file to transcribe detected. Hold down the key for a longer time.')
            return

        print('Writing audio to file...')

        # write microphone audio to file
        # This is usually a uniquely generated path, simplified for now.
        audio_path = str(BASE_DIR /  "output.mp3" )

        with wave.open(audio_path, 'wb') as wf:
            wf.setnchannels(MIC_CHANNELS)
            wf.setsampwidth(p.get_sample_size(FORMAT))
            wf.setframerate(MIC_SAMPLING_RATE)
            wf.writeframes(b''.join(frames))
        
        print("Temporarily saved to " + audio_path)

        try: Thread( target=send_audio_to_server, args=[audio_path] ).start()
        except: traceback.print_exc()
        
        return
    
    except: traceback.print_exc()    

def send_audio_to_server(audio_file):
    
    url = 'http://127.0.0.1:5000/process_audio'

    settings = None

    #try: settings = json.load( open('settings.json') )
    #except OSError:
        #return print("Could not open settings.json! Possibly occupied. Disregarding this request.")
        

    data = {
        'audio_file': audio_file, 
        "device_ids": [],
        "author": "listener"
        }

    print("Sending speech request to server...")

    try: response = requests.post(url, json=data, timeout=40)
    except: traceback.print_exc()

    print('retrieved response. attempting to jsonify.')

    # Rest of the code is not relevant.

''' Main process '''

if __name__ == '__main__':

    faulthandler.enable()
    
    while True:
            
        CHUNK = 1024
        FORMAT = pyaudio.paInt16

        p = pyaudio.PyAudio()
        if MIC is None:
            MIC = p.get_default_input_device_info()['index']

        SPEAKER = p.get_default_output_device_info()['index']

        # get channels and sampling rate of mic
        mic_info = p.get_device_info_by_index(MIC)
        MIC_CHANNELS = mic_info['maxInputChannels']
        MIC_SAMPLING_RATE = 40000

        print('Local listener is booting up...')

        frames = []
        recording = False
        stream = None

        try:

            keyboard.on_press_key(MIC_RECORD_KEY, on_press_key)
            keyboard.on_release_key(MIC_RECORD_KEY, on_release_key)

            print('Local listener is ready')

            while True:

                try:
                    if recording and stream:
                        data = stream.read(CHUNK)
                        frames.append(data)
                    else:
                        sleep(0.2)

                except:
                    traceback.print_exc()
                    exit(1)

        except:
            traceback.print_exc()
            exit(1)

Here is what the error looks like:

Windows fatal exception: code 0xc0000374

Thread 0x00005934 (most recent call first):
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesurllib3utilconnection.py", line 73 in create_connection
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesurllib3connection.py", line 196 in _new_conn
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesurllib3connection.py", line 236 in connect
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libhttpclient.py", line 975 in send
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libhttpclient.py", line 1037 in _send_output
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libhttpclient.py", line 1277 in endheaders
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesurllib3connection.py", line 398 in request
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesurllib3connectionpool.py", line 495 in _make_request
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesurllib3connectionpool.py", line 789 in urlopen
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesrequestsadapters.py", line 667 in send
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesrequestssessions.py", line 703 in send
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesrequestssessions.py", line 589 in request
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesrequestsapi.py", line 59 in request
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagesrequestsapi.py", line 115 in post
  File "C:UsersDhruvDesktoppyAudioProcessorWhispertest.py", line 119 in send_audio_to_server (Referring to "try: response = requests.post(url,  json=data,  timeout=40)")
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 953 in run
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 1016 in _bootstrap_inner
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 973 in _bootstrap

Thread 0x00006464 (most recent call first):
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 320 in wait
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libqueue.py", line 171 in get
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packageskeyboard_generic.py", line 57 in process
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 953 in run
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 1016 in _bootstrap_inner
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 973 in _bootstrap

Thread 0x00000b54 (most recent call first):
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packageskeyboard_winkeyboard.py", line 563 in listen
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packageskeyboard__init__.py", line 294 in listen
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 953 in run
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 1016 in _bootstrap_inner
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libthreading.py", line 973 in _bootstrap

Current thread 0x00006be4 (most recent call first):
  File "C:UsersDhruvAppDataLocalProgramsPythonPython310libsite-packagespyaudio__init__.py", line 570 in read
  File "C:UsersDhruvDesktoppyAudioProcessorWhispertest.py", line 165 in <module> (Referring to "data = stream.read(CHUNK)")

Could I be doing something wrong here?
Would appreciate some guidance.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật