LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-28-2023, 12:41 PM   #1
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 17

Rep: Reputation: 0
Doing a record in Python with a microphone hangs the thread and prevents play until reboot


My recording from a microphone plays fine when I boot and play a recording that I recorded before the boot. This is true using any and all play libraries, including my script. But when record a phrase and then immediately try to play it, it hangs on stream = p.open(). When I use it with "with", it generates an AttributeError. I'm running Ubuntu.

Source code:

Code:
def recordCommand(fileName):
    # the file name output you want to record into
    filename = "recorded.wav"
    # set the chunk size of 1024 samples
    chunk = 1024
    # sample format
    FORMAT = pyaudio.paInt16
#    FORMAT = pyaudio.paInt24
    # mono, change to 2 if you want stereo
#    channels = 2
    channels = 1
    # 44100 samples per second
    sample_rate = 44100
    record_seconds = 5
    # initialize PyAudio object
    p = pyaudio.PyAudio()
    # open stream object as input & output



##changed from here down
#    stream = p.open(format=FORMAT,
#                    channels=channels,
#                    rate=sample_rate,
#                    input=True,
#                    output=True,
#                    frames_per_buffer=chunk)



    with p.open(format=FORMAT,
                channels=channels,
                rate=sample_rate,
                input=True,
                output=True,
                frames_per_buffer=chunk) as stream:
        frames = []
        print("Recording...")
        for i in range(int(sample_rate / chunk * record_seconds)):
            data = stream.read(chunk)
            # if you want to hear your voice while recording
            # stream.write(data)
            frames.append(data)
        print("Finished recording.")
        # stop and close stream
        stream.stop_stream()
        stream.close()
        # terminate pyaudio object
        p.terminate()
        # save audio file
        # open the file in 'write bytes' mode
        wf = wave.open(filename, "wb")
        # set the channels
        wf.setnchannels(channels)
        # set the sample format
        wf.setsampwidth(p.get_sample_size(FORMAT))
        # set the sample rate
        wf.setframerate(sample_rate)
        # write the frames as bytes
        wf.writeframes(b"".join(frames))
        # close the file
        wf.close()

Last edited by Squirrel1; 04-28-2023 at 03:35 PM. Reason: Added [code] tags
 
Old 04-28-2023, 12:48 PM   #2
Turbocapitalist
LQ Guru
 
Registered: Apr 2005
Distribution: Linux Mint, Devuan, OpenBSD
Posts: 7,583
Blog Entries: 4

Rep: Reputation: 3879Reputation: 3879Reputation: 3879Reputation: 3879Reputation: 3879Reputation: 3879Reputation: 3879Reputation: 3879Reputation: 3879Reputation: 3879Reputation: 3879
Welcome.

Can you please edit your post above to wrap the Python script in [code] [/code] tags so that your indentation is retained? Given the importance of indentation in Python this is essential to understanding your script.
 
Old 04-28-2023, 03:27 PM   #3
teckk
LQ Guru
 
Registered: Oct 2004
Distribution: Arch
Posts: 5,306
Blog Entries: 6

Rep: Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908
To the OP, that's a mess. It's python. Can't even tell where your first function ends. You also don't have any imports.

Quote:
But when record a phrase and then immediately try to play it, it hangs on stream = p.open(). When I use it with "with", it generates an AttributeError.
Look at try: and except:

Post python and other source code like this try-except example:
Code:
#!/usr/bin/python

from urllib import request, error
from html2text import html2text, HTML2Text
from pydoc import pager

agent = ('Mozilla/5.0 (Windows NT 10.0; Win64 x64; rv:110.0) '
            'Gecko/20100101 Firefox/110.0')

user_agent = {'User-Agent': agent,
            'Accept': 'text/html,application/xhtml+xml,'
            'application/xml;q=0.9,*/*;q=0.8',
            'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
            'Accept-Encoding': 'none',
            'Accept-Language': 'en-US,en;q=0.8',
            'Connection': 'keep-alive'}
            
class TextBrowser():
    def __init__(self, Page):
        def loadPage(): 
            try:
                req = request.Request(Page, data=None, headers=user_agent)
                page = request.urlopen(req)
            except error.HTTPError as e:
                print("Http error")
            except error.URLError as e:
                print('Url Error')
            except TypeError as e:
                print('Type Error')
            except ValueError as e:
                print("Value error")
                
            try:
                html = page.read().decode('utf-8', 'ignore')
            except NameError:
                print('Name error')
                
            return html
            
        def html2txtBrowse():
            self.p = loadPage()
            noLinks = HTML2Text()
            noLinks.ignore_links = True
            txt = noLinks.handle(self.p)
            #print(txt)
            pager(txt) #Arrows. PgUp/Down to scroll
            
        html2txtBrowse()
            
if __name__ == "__main__":
    
    Page = input('Enter/Paste url to view :')
    
    TextBrowser(Page)
Someone can copy and paste that into a text editor and run it.
 
Old 04-29-2023, 04:03 PM   #4
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 17

Original Poster
Rep: Reputation: 0
Sorry about that. My intention was to focus on the broken code and leave out the distractions. But if you want to run my code, you will need more. This should run right out of the window. Thanks in advance:

Code:
import numpy as np 
import sounddevice as sd
import soundfile as sf
import pyaudio
import wave


def playCommand(fileString):
    print("entering playCommand")

    print("fileString = " + fileString)
    filename = fileString + '.wav'
    print("calling sf.read()")
    # Extract data and sampling rate from file
    data, fs = sf.read(filename, dtype='float32')  
    status = sd.wait()  # Wait until file is done playing
    print("sd.wait() status = " + str(status))
#    data, fs = sf.read(filename, dtype='float24')  
#    sd.play(data, fs)
    from playsound import playsound
    playsound(fileString + '.wav')


#    myFormat = soundfile.available_formats()
#    print("myFormat = " + str(myFormat))

    print("commandFileName = " + commandFileName)


def recordCommand(fileName):
    # the file name output you want to record into
#    filename = "recorded.wav"
    # set the chunk size of 1024 samples
    chunk = 1024
    # sample format
    FORMAT = pyaudio.paInt16
#    FORMAT = pyaudio.paInt24
    # mono, change to 2 if you want stereo
#    channels = 2
    channels = 1
    # 44100 samples per second
    sample_rate = 44100
    # initialize PyAudio object
    p = pyaudio.PyAudio()
    # open stream object as input & output

    stream = p.open(format=FORMAT,
                    channels=channels,
                    rate=sample_rate,
                    input=True,
                    output=True,
                    frames_per_buffer=chunk)



#    with p.open(format=FORMAT,
#                channels=channels,
#                rate=sample_rate,
#                input=True,
#                output=True,
#                frames_per_buffer=chunk) as stream:
    frames = []
    print("Recording...")
    for i in range(int(sample_rate / chunk * seconds)):
        data = stream.read(chunk)
        # if you want to hear your voice while recording
        # stream.write(data)
        frames.append(data)
    print("Finished recording.")
    # stop and close stream
    stream.stop_stream()
    stream.close()
    # terminate pyaudio object
    p.terminate()
    # save audio file
    # open the file in 'write bytes' mode
    wf = wave.open(fileName + ".wav", "wb")
    # set the channels
    wf.setnchannels(channels)
    # set the sample format
    wf.setsampwidth(p.get_sample_size(FORMAT))
    # set the sample rate
    wf.setframerate(sample_rate)
    # write the frames as bytes
    wf.writeframes(b"".join(frames))
    # close the file
    wf.close()


fs = 44100  # Sample rate
seconds = 3.0  # Duration of recording

commandFileName = "command"
#commandFilePath = commandFileName + ".wav"
yorn = input("Record new command? (y/n)")
if (yorn == 'y'):
#    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
#    sd.wait()  # Wait until recording is finished
#    print("commandFileName = " + commandFileName)
#    write(commandFileName+".wav", fs, myrecording)  # Save as WAV file 

    recordCommand(commandFileName)

print("Calling playCommand")
playCommand(commandFileName)
 
Old 05-02-2023, 10:14 PM   #5
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 17

Original Poster
Rep: Reputation: 0
Is there someone out there who knows something about wave files and can let me know why my records with microphone hang the thread? I'm getting ready to file a bug against the project. Thanks so much!
 
Old 05-03-2023, 09:56 AM   #6
teckk
LQ Guru
 
Registered: Oct 2004
Distribution: Arch
Posts: 5,306
Blog Entries: 6

Rep: Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908Reputation: 1908
Try this:

pyaud.py
Code:
#!/usr/bin/python

import pyaudio
import wave
 
Fmt = pyaudio.paInt16
Chan = 1
Rate = 44100
Chunk = 512
RecSec = 5
OutputFile = "recordedFile.wav"
audio = pyaudio.PyAudio()

print("\nDevice list:\n")
info = audio.get_host_api_info_by_index(0)
numdevices = info.get('deviceCount')
for i in range(0, numdevices):
        if (audio.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
            print("Input Device id ", i, " - ", audio.get_device_info_by_host_api_device_index(0, i).get('name'))

print("\n")

index = int(input('Input a number :'))
print("recording via index "+str(index))

stream = audio.open(format=Fmt, channels=Chan, rate=Rate, input=True, input_device_index = index, frames_per_buffer=Chunk)
print ("recording started")
Recordframes = []
 
for i in range(0, int(Rate / Chunk * RecSec)):
    data = stream.read(Chunk)
    Recordframes.append(data)
print ("recording stopped")

stream.stop_stream()
stream.close()
audio.terminate()
 
with wave.open(OutputFile, 'wb') as f:
    f.setnchannels(Chan)
    f.setsampwidth(audio.get_sample_size(Fmt))
    f.setframerate(Rate)
    f.writeframes(b''.join(Recordframes))
 
Old 05-10-2023, 04:11 PM   #7
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 17

Original Poster
Rep: Reputation: 0
Thanks, that solved my problem.
 
Old 05-22-2024, 03:22 PM   #8
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 17

Original Poster
Rep: Reputation: 0
Another problem with recording from a microphone

About one time in 5 when I run this code, it generates the below error. The code is:


def recordCommand(fileString):
#Fmt = pyaudio.paInt16audio
Chan = 1
Fmt = pyaudio.paInt24
#Chan = 2
sr = 44100
Chunk = 512
#Chunk = 1024
RecSec = 3
OutputFile = "Command.wav"
audio = pyaudio.PyAudio()

# print("\nDevice list:\n")
# info = audio.get_host_api_info_by_index(0)
# numdevices = info.get('deviceCount')
# for i in range(0, numdevices):
# if (audio.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
# print("Input Device id ", i, " - ", audio.get_device_info_by_host_api_device_index(0, i).get('name'))

# print("\n")

# index = int(input('Input a number :'))
# print("recording via index "+str(index))

# stream = audio.open(format=Fmt, channels=Chan, rate=Rate, input=True, input_device_index = index, frames_per_buffer=Chunk)
stream = audio.open(format=Fmt, channels=Chan, rate=sr, input=True, input_device_index = 0, frames_per_buffer=Chunk)
print ("recording started")
Recordframes = []

for i in range(0, int(sr / Chunk * RecSec)):
data = stream.read(Chunk)
Recordframes.append(data)
print ("recording stopped")

stream.stop_stream()
stream.close()
audio.terminate()

print("OutputFile = " + OutputFile)
with wave.open(OutputFile, 'wb') as f:
f.setnchannels(Chan)
f.setsampwidth(audio.get_sample_size(Fmt))
f.setframerate(sr)
f.writeframes(b''.join(Recordframes))




and the error is:


ALSA lib pcm.c:2664:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2664:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2664:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
ALSA lib pcm_oss.c:397:(_snd_pcm_oss_open) Cannot open device /dev/dsp
ALSA lib pcm_oss.c:397:(_snd_pcm_oss_open) Cannot open device /dev/dsp
ALSA lib confmisc.c:160:(snd_config_get_card) Invalid field card
ALSA lib pcm_usb_stream.c:482:(_snd_pcm_usb_stream_open) Invalid card 'card'
ALSA lib confmisc.c:160:(snd_config_get_card) Invalid field card
ALSA lib pcm_usb_stream.c:482:(_snd_pcm_usb_stream_open) Invalid card 'card'
recording started
Traceback (most recent call last):
File "/home/waveformScan.py", line 631, in <module>
recordCommand(topCommandWOWav)
File "/home/waveformScan.py", line 118, in recordCommand
data = stream.read(Chunk)
File "/home/miniconda3/lib/python3.9/site-packages/pyaudio/__init__.py", line 570, in read
return pa.read_stream(self._stream, num_frames,
OSError: [Errno -9981] Input overflowed


Can someone suggest something about how to get around this error? It's really annoying. Thanks!

Last edited by Squirrel1; 05-22-2024 at 04:04 PM.
 
Old 05-23-2024, 12:42 AM   #9
NevemTeve
Senior Member
 
Registered: Oct 2011
Location: Budapest
Distribution: Debian/GNU/Linux, AIX
Posts: 4,937
Blog Entries: 1

Rep: Reputation: 1894Reputation: 1894Reputation: 1894Reputation: 1894Reputation: 1894Reputation: 1894Reputation: 1894Reputation: 1894Reputation: 1894Reputation: 1894Reputation: 1894
Kindly format your code with [code] and [/code] tags.
Also make sure not to use uninitialized variables (in this code `index` is uninitialized).

Last edited by NevemTeve; 05-23-2024 at 12:49 AM.
 
Old 05-31-2024, 05:26 PM   #10
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 17

Original Poster
Rep: Reputation: 0
Doing a record in Python with a microphone hangs the thread and prevents play until reboot

Try this. Keep in mind that it only crashes about one time in five so you might have to run it about a dozen or so times to generate this error. Also keep in mind that someone on the forum suggested this solution as an alternative to the one that I was using that hung the machine until reboot.



A solution that was posted in thread:

https://www.linuxquestions.org/quest...ot-4175724557/

crashes about one time in five when I run it. The error message I get when this happens is:

ALSA lib pcm.c:2664:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2664:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2664:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:877:(find_matching_chmap) Found no matching channel map
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
ALSA lib pcm_oss.c:397:(_snd_pcm_oss_open) Cannot open device /dev/dsp
ALSA lib pcm_oss.c:397:(_snd_pcm_oss_open) Cannot open device /dev/dsp
ALSA lib confmisc.c:160:(snd_config_get_card) Invalid field card
ALSA lib pcm_usb_stream.c:482:(_snd_pcm_usb_stream_open) Invalid card 'card'
ALSA lib confmisc.c:160:(snd_config_get_card) Invalid field card
ALSA lib pcm_usb_stream.c:482:(_snd_pcm_usb_stream_open) Invalid card 'card'
recording started
Traceback (most recent call last):
File "/home/My_Directory/Non_hanging_recording_solution.py", line 340, in <module>
recordCommand(commandFileName)
File "/home/My_Directory/Non_hanging_recording_solution.py", line 56, in recordCommand
data = stream.read(Chunk)
File "/home/miniconda3/lib/python3.9/site-packages/pyaudio/__init__.py", line 570, in read
return pa.read_stream(self._stream, num_frames,
OSError: [Errno -9981] Input overflowed


Then two or three executions in a row will fail and then it will work again with no changes to the code.

Simplified code for this is:

Code:
#!/usr/bin/python

import numpy as np 
import pyaudio
import wave
from playsound import playsound
from array import *
import soundfile as sf




def recordCommand(fileString):
    #Fmt = pyaudio.paInt16audio
    Chan = 1
    Fmt = pyaudio.paInt24
    sr = 44100
    Chunk = 512
    #Chunk = 1024
    RecSec = 3
    OutputFile = "myWavFile.wav"
    audio = pyaudio.PyAudio()

#    print("\nDevice list:\n")
#    info = audio.get_host_api_info_by_index(0)
#    numdevices = info.get('deviceCount')
#    for i in range(0, numdevices):
#        if (audio.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels')) > 0:
#            print("Input Device id ", i, " - ", audio.get_device_info_by_host_api_device_index(0, i).get('name'))

 #   print("\n")

#    index = int(input('Input a number :'))
#    print("recording via index "+str(index))

#    stream = audio.open(format=Fmt, channels=Chan, rate=Rate, input=True, input_device_index = index, frames_per_buffer=Chunk)
    stream = audio.open(format=Fmt, channels=Chan, rate=sr, input=True, input_device_index = 0, frames_per_buffer=Chunk)
    print ("recording started")
    Recordframes = []
 
    for i in range(0, int(sr / Chunk * RecSec)):
        data = stream.read(Chunk)
        Recordframes.append(data)
    print ("recording stopped")

    stream.stop_stream()
    stream.close()
    audio.terminate()

    print("OutputFile = " + OutputFile) 
    with wave.open(OutputFile, 'wb') as f:
        f.setnchannels(Chan)
        f.setsampwidth(audio.get_sample_size(Fmt))
        f.setframerate(sr)
        f.writeframes(b''.join(Recordframes))

        
        
def playCommand(fileString):
    print("fileString = " + fileString)
 
    playsound(fileString)


fileName = "myWavFile.wav"
recordCommand(fileName)
playCommand(fileName)
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Opening/launching Synaptic prevents a reboot edhe1 Linux Mint 9 09-18-2021 04:41 AM
Creating a sudo group that provides read access but prevents reboot Viper786 Linux - Newbie 1 05-29-2019 10:21 PM
ATA password prevents reboot ernstlenzer Linux - Software 4 05-18-2014 07:00 AM
LXer: Python Python Python (aka Python 3) LXer Syndicated Linux News 0 08-05-2009 09:30 PM
Installation of Redhat AS2 prevents me from doing anything gregorian Linux - Newbie 4 05-17-2006 02:36 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 10:33 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration