Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Access violation (0xC0000005) on Windows when opening two different microphones on separate threads #696

Open
lugia19 opened this issue Jun 6, 2023 · 0 comments

Comments

@lugia19
Copy link

lugia19 commented Jun 6, 2023

Steps to reproduce

Here's some code that reliably causes the issue:

import threading
import speech_recognition as sr

def start_rec(srMic, srRecognizer):
    with srMic as source:
        while True:
            print("Listening for audio...")
            audio = srRecognizer.listen(source)


def main():
    #5 and 1 are both real microphones
    srMic1 = sr.Microphone(device_index=5)
    srRecognizer1 = sr.Recognizer()
    thread1 = threading.Thread(target=start_rec, args=(srMic1, srRecognizer1))

    srMic2 = sr.Microphone(device_index=1)
    srRecognizer2 = sr.Recognizer()
    thread2 = threading.Thread(target=start_rec, args=(srMic2, srRecognizer2))

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

if __name__ == "__main__":
    main()

Expected behaviour

It should begin listening on both devices.

Actual behaviour

I get an access violation.

System information

Running on windows 10, latest version of the library.

Fix

Use a lock to ensure only one thread opens a microphone at a time.

import threading
import speech_recognition as sr
srLock = threading.Lock()

def start_rec(srMic, srRecognizer):
    srLock.acquire()
    with srMic as source:
        srLock.release()
        while True:
            print("Listening for audio...")
            audio = srRecognizer.listen(source)


def main():
    srMic1 = sr.Microphone(device_index=5)
    srRecognizer1 = sr.Recognizer()
    thread1 = threading.Thread(target=start_rec, args=(srMic1, srRecognizer1))

    srMic2 = sr.Microphone(device_index=1)
    srRecognizer2 = sr.Recognizer()
    thread2 = threading.Thread(target=start_rec, args=(srMic2, srRecognizer2))

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

if __name__ == "__main__":
    main()
@lugia19 lugia19 changed the title Access violation on Windows when opening two different microphones on separate threads Access violation (0xC0000005) on Windows when opening two different microphones on separate threads Jun 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant