Hello! It looks like you're encountering ALSA (Advanced Linux Sound Architecture) errors related to microphone access when running your Python script. These errors typically occur when the script tries to access audio devices that are either unavailable, misconfigured, or not present on your system.
To help you resolve these issues, I'll provide several modifications and suggestions:
- Make Microphone Access Optional and Handle Exceptions Gracefully
- Provide Clear Instructions on Using Audio Files Instead of a Microphone
- Enhance Logging for Better Debugging
1. Make Microphone Access Optional and Handle Exceptions Gracefully
We'll modify the record_microphone function to handle exceptions when attempting to access the microphone. If the microphone cannot be accessed, the script will notify the user and continue running without microphone input.
# -*- encoding: utf-8 -*-
import os
import ssl
import asyncio
import argparse
import json
import logging
import traceback
from multiprocessing import Process
from queue import Queue
# Additional imports
import time
import websockets
try:
import pyaudio
except ImportError:
pyaudio = None # Microphone input will not be available
logging.basicConfig(level=logging.INFO) # Changed to INFO for better visibility
parser = argparse.ArgumentParser()
parser.add_argument(
"--host", type=str, default="localhost", required=False, help="Host IP (e.g., localhost, 0.0.0.0)"
)
parser.add_argument("--port", type=int, default=10095, required=False, help="WebSocket server port")
parser.add_argument("--chunk_size", type=str, default="5,10,5", help="Chunk sizes in milliseconds")
parser.add_argument("--encoder_chunk_look_back", type=int, default=4, help="Encoder chunk look-back")
parser.add_argument("--decoder_chunk_look_back", type=int, default=0, help="Decoder chunk look-back")
parser.add_argument("--chunk_interval", type=int, default=10, help="Chunk interval in milliseconds")
parser.add_argument(
"--hotword",
type=str,
default="",
help="Hotword file path, one hotword per line (e.g., '阿里巴巴 20')",
)
parser.add_argument("--audio_in", type=str, default=None, help="Input audio file or SCP file")
parser.add_argument("--audio_fs", type=int, default=16000, help="Audio sampling rate")
parser.add_argument(
"--send_without_sleep",
action="store_true",
default=True,
help="If audio_in is set, send without sleep",
)
parser.add_argument("--thread_num", type=int, default=1, help="Number of threads")
parser.add_argument("--words_max_print", type=int, default=10000, help="Maximum words to print")
parser.add_argument("--output_dir", type=str, default=None, help="Output directory")
parser.add_argument("--ssl", type=int, default=1, help="1 for SSL connection, 0 for no SSL")
parser.add_argument("--use_itn", type=int, default=1, help="1 for using ITN, 0 for not using ITN")
parser.add_argument("--mode", type=str, default="2pass", help="Mode: offline, online, 2pass")
args = parser.parse_args()
args.chunk_size = [int(x) for x in args.chunk_size.split(",")]
print(args)
# Global variables
voices = Queue()
offline_msg_done = False
websocket = None # Global websocket variable
# Create output directory if it doesn't exist
if args.output_dir is not None:
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
async def record_microphone():
global voices, websocket
if pyaudio is None:
logging.error("pyaudio is not installed. Microphone recording is unavailable.")
return
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = args.audio_fs
# Calculate chunk size
chunk_duration_ms = 60 * args.chunk_size[1] / args.chunk_interval
CHUNK = int(RATE * chunk_duration_ms / 1000)
p = pyaudio.PyAudio()
try:
stream = p.open(
format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK
)
except Exception as e:
logging.error(f"Failed to open microphone stream: {e}")
p.terminate()
return
# Prepare hotwords
hotword_msg = prepare_hotwords(args.hotword)
use_itn = args.use_itn == 1
message = json.dumps(
{
"mode": args.mode,
"chunk_size": args.chunk_size,
"chunk_interval": args.chunk_interval,
"encoder_chunk_look_back": args.encoder_chunk_look_back,
"decoder_chunk_look_back": args.decoder_chunk_look_back,
"wav_name": "microphone",
"is_speaking": True,
"hotwords": hotword_msg,
"itn": use_itn,
}
)
await websocket.send(message)
try:
while True:
data = stream.read(CHUNK)
await websocket.send(data)
await asyncio.sleep(0.005)
except Exception as e:
logging.error(f"An error occurred during microphone recording: {e}")
finally:
stream.stop_stream()
stream.close()
p.terminate()
# Rest of the code remains unchanged...
# (For brevity, not repeating the entire script. Ensure you include similar logging and exception handling in other functions.)
# ... [Rest of your existing code] ...
if __name__ == "__main__":
if args.audio_in is None:
# Microphone input
logging.info("Starting microphone recording...")
process = Process(target=one_thread, args=(0, 0, 0))
process.start()
process.join()
logging.info("Microphone recording ended.")
else:
# Audio file input
if args.audio_in.endswith(".scp"):
with open(args.audio_in, "r") as f:
wavs = f.readlines()
else:
wavs = [args.audio_in]
total_files = len(wavs)
if total_files >= args.thread_num:
files_per_thread = total_files // args.thread_num
extra_files = total_files % args.thread_num
else:
files_per_thread = 1
extra_files = 0
processes = []
chunk_begin = 0
for i in range(args.thread_num):
current_chunk_size = files_per_thread + (1 if i < extra_files else 0)
p = Process(target=one_thread, args=(i, chunk_begin, current_chunk_size))
chunk_begin += current_chunk_size
p.start()
processes.append(p)
for p in processes:
p.join()
logging.info("Audio file processing ended.")
2. Use Audio Files Instead of a Microphone
If your environment doesn't have a functioning microphone or you prefer to use pre-recorded audio files, you can modify your script to process audio files instead of attempting to access the microphone. Here's how you can do it:
-
Prepare Your Audio Files:
- Ensure your audio files are in a supported format (e.g.,
.wav, .pcm).
- If you have multiple files, you can create a
.scp file (a simple text file) listing all your audio files, one per line.
-
Run the Script with the --audio_in Argument:
By providing the --audio_in argument, the script will bypass the microphone recording and process the specified audio files instead, avoiding the ALSA errors related to microphone access.
3. Enhance Logging for Better Debugging
Switching the logging level from ERROR to INFO (as done in the modified script) provides more visibility into what the script is doing. This can help in understanding the flow and identifying where issues might be occurring.
Additional Recommendations
-
Check Audio Device Availability:
Ensure that your system has a microphone connected and properly configured. You can list available audio devices using the following Python snippet:
import pyaudio
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
info = p.get_device_info_by_index(i)
print(f"Device {i}: {info['name']}")
p.terminate()
This will help you verify if PyAudio can detect any input devices.
-
Use Virtual Audio Devices (If Necessary):
If you're running the script on a server or an environment without physical audio devices, consider using virtual audio devices like ALSA's dummy driver. This way, PyAudio believes there is an audio device available.
-
Install and Configure ALSA Properly:
Ensure that ALSA is correctly installed and configured on your system. Missing or misconfigured ALSA settings can lead to the errors you've encountered.
-
Update PyAudio or Use Alternatives:
PyAudio can sometimes be finicky, especially across different systems. Consider using alternatives like sounddevice which might offer better compatibility and easier setup.
Summary
By making microphone access optional and handling exceptions gracefully, you can prevent the script from crashing due to ALSA errors. Additionally, using pre-recorded audio files can be a more reliable alternative, especially in environments without readily available audio input devices.
If you continue to face issues, please provide more details about your operating environment (e.g., operating system, availability of audio devices), and I'll be happy to assist further!