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 |
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Are you new to LinuxQuestions.org? Visit the following links:
Site Howto |
Site FAQ |
Sitemap |
Register Now
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
|
|
04-28-2023, 12:41 PM
|
#1
|
LQ Newbie
Registered: Apr 2023
Posts: 17
Rep:
|
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
|
|
|
04-28-2023, 12:48 PM
|
#2
|
LQ Guru
Registered: Apr 2005
Distribution: Linux Mint, Devuan, OpenBSD
Posts: 7,583
|
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.
|
|
|
04-28-2023, 03:27 PM
|
#3
|
LQ Guru
Registered: Oct 2004
Distribution: Arch
Posts: 5,306
|
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.
|
|
|
04-29-2023, 04:03 PM
|
#4
|
LQ Newbie
Registered: Apr 2023
Posts: 17
Original Poster
Rep:
|
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)
|
|
|
05-02-2023, 10:14 PM
|
#5
|
LQ Newbie
Registered: Apr 2023
Posts: 17
Original Poster
Rep:
|
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!
|
|
|
05-03-2023, 09:56 AM
|
#6
|
LQ Guru
Registered: Oct 2004
Distribution: Arch
Posts: 5,306
|
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))
|
|
|
05-10-2023, 04:11 PM
|
#7
|
LQ Newbie
Registered: Apr 2023
Posts: 17
Original Poster
Rep:
|
Thanks, that solved my problem.
|
|
|
05-22-2024, 03:22 PM
|
#8
|
LQ Newbie
Registered: Apr 2023
Posts: 17
Original Poster
Rep:
|
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.
|
|
|
05-23-2024, 12:42 AM
|
#9
|
Senior Member
Registered: Oct 2011
Location: Budapest
Distribution: Debian/GNU/Linux, AIX
Posts: 4,937
|
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.
|
|
|
05-31-2024, 05:26 PM
|
#10
|
LQ Newbie
Registered: Apr 2023
Posts: 17
Original Poster
Rep:
|
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)
|
|
|
All times are GMT -5. The time now is 10:33 PM.
|
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.
|
Latest Threads
LQ News
|
|