LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
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, 11:41 AM   #1
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 16

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 02:35 PM. Reason: Added [code] tags
 
Old 04-28-2023, 11:48 AM   #2
Turbocapitalist
LQ Guru
 
Registered: Apr 2005
Distribution: Linux Mint, Devuan, OpenBSD
Posts: 7,345
Blog Entries: 3

Rep: Reputation: 3756Reputation: 3756Reputation: 3756Reputation: 3756Reputation: 3756Reputation: 3756Reputation: 3756Reputation: 3756Reputation: 3756Reputation: 3756Reputation: 3756
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, 02:27 PM   #3
teckk
LQ Guru
 
Registered: Oct 2004
Distribution: Arch
Posts: 5,151
Blog Entries: 6

Rep: Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835
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, 03:03 PM   #4
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 16

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, 09:14 PM   #5
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 16

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, 08:56 AM   #6
teckk
LQ Guru
 
Registered: Oct 2004
Distribution: Arch
Posts: 5,151
Blog Entries: 6

Rep: Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835Reputation: 1835
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, 03:11 PM   #7
Squirrel1
LQ Newbie
 
Registered: Apr 2023
Posts: 16

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

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 03:04 PM.
 
Old 05-22-2024, 11:42 PM   #9
NevemTeve
Senior Member
 
Registered: Oct 2011
Location: Budapest
Distribution: Debian/GNU/Linux, AIX
Posts: 4,879
Blog Entries: 1

Rep: Reputation: 1871Reputation: 1871Reputation: 1871Reputation: 1871Reputation: 1871Reputation: 1871Reputation: 1871Reputation: 1871Reputation: 1871Reputation: 1871Reputation: 1871
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-22-2024 at 11:49 PM.
 
  


Reply



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 03:41 AM
Creating a sudo group that provides read access but prevents reboot Viper786 Linux - Newbie 1 05-29-2019 09:21 PM
ATA password prevents reboot ernstlenzer Linux - Software 4 05-18-2014 06:00 AM
LXer: Python Python Python (aka Python 3) LXer Syndicated Linux News 0 08-05-2009 08:30 PM
Installation of Redhat AS2 prevents me from doing anything gregorian Linux - Newbie 4 05-17-2006 01:36 AM

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

All times are GMT -5. The time now is 11:07 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