You're absolutely right! termux-microphone-record is a simple wrapper for fixed-duration recording, which is far from ideal for a voice assistant that needs to intelligently detect when you start and stop speaking.
The core challenge for a voice assistant isn't just recording, but Voice Activity Detection (VAD) and silence detection to accurately segment speech. This allows you to capture only the relevant spoken phrases for Speech-to-Text (STT) processing, rather than long periods of silence.
Here's a test script exploring several methods in Termux that go beyond basic recording, focusing on VAD and silence detection.
Prerequisites in Termux
First, ensure you have the necessary packages and permissions.
pkg update && pkg upgrade
pkg install sox ffmpeg python python-pip termux-api
# Grant microphone permission (Termux will prompt you)
termux-microphone-record # Just run this once to ensure permission is granted
# If not granted, manually check Termux app info -> Permissions -> Microphone
# Install Python libraries
pip install pyaudio webrtcvad pydub SpeechRecognition
# For pyaudio in Termux, you might need some additional setup for the audio backend
# Pyaudio typically uses PortAudio, which connects to ALSA on Linux.
# Termux's audio setup can be a bit finicky.
# If pyaudio throws errors, ensure `libportaudio` is installed:
pkg install libportaudio
The Test Script (voice_assistant_methods.sh)
Create a file named voice_assistant_methods.sh and paste the following content:
#!/data/data/com.termux/files/usr/bin/bash
# --- Configuration ---
OUTPUT_DIR="/data/data/com.termux/files/home/voice_assistant_recordings"
RECORD_SRATE="16000" # Sample rate (Hz) - common for speech
RECORD_CHANNELS="1" # Mono
RECORD_FORMAT="s16_le" # Signed 16-bit Little Endian
RECORD_BITS="16"
# Create output directory
mkdir -p "$OUTPUT_DIR"
echo "Recordings will be saved in: $OUTPUT_DIR"
echo "---------------------------------------------------"
# --- Method 1: Using SoX (Sound eXchange) for Silence Detection ---
# SoX is incredibly powerful for audio manipulation and can detect silence.
# This method records until a period of silence is detected.
echo "### METHOD 1: SoX with Silence Detection ###"
echo " - Records until silence is detected."
echo " - Speak a phrase, then be silent for ~1 second."
echo " - Press Ctrl+C to stop if it records too long."
echo ""
SOX_OUTPUT="$OUTPUT_DIR/sox_silence_$(date +%Y%m%d_%H%M%S).wav"
echo " (Listening for speech...)"
# Explanation of sox silence parameters:
# silence [initial_duration] [threshold_initial_volume]% [final_duration] [threshold_final_volume]%
# Example: silence 1 0.1% 1 1.0%
# - Start recording immediately (1 second of silence at 0.1% volume will trigger stop if recording nothing)
# - If recording, stop if 1 second of silence at 1.0% volume is detected.
# Note: Adjust thresholds (e.g., 0.1%, 1.0%) based on your environment's background noise.
# Lower percentage = more sensitive.
sox -V0 -t "$RECORD_FORMAT" -r "$RECORD_SRATE" -c "$RECORD_CHANNELS" -b "$RECORD_BITS" \
--input-buffer 8192 \
-d "$SOX_OUTPUT" \
silence 1 0.1% 1 "$RECORD_SRATE"s 1.0% 2>&1 | grep -v 'Input file' | grep -v 'Output file'
echo " Recording saved to: $SOX_OUTPUT"
echo ""
# --- Method 2: Using SoX (Sound eXchange) with VAD (Voice Activity Detection) ---
# SoX also has a 'vad' effect which is specifically designed for VAD.
# This is often more robust than simple silence detection for speech.
echo "### METHOD 2: SoX with VAD (Voice Activity Detection) ###"
echo " - Records, analyzing speech activity."
echo " - Speak a phrase, then be silent for ~1 second."
echo " - Press Ctrl+C to stop if it records too long."
echo ""
SOX_VAD_OUTPUT="$OUTPUT_DIR/sox_vad_$(date +%Y%m%d_%H%M%S).wav"
echo " (Listening for speech...)"
# Explanation of sox vad parameters:
# vad [attack_duration [decay_duration [threshold [spike_duration]]]]
# attack_duration: How long speech must be continuous to be detected (e.g., 0.2s)
# decay_duration: How long silence must be continuous to stop detecting speech (e.g., 0.5s)
# threshold: Relative threshold of speech volume (e.g., 6% of max volume)
# spike_duration: Ignores short spikes of noise (e.g., 0.1s)
# Note: These values are examples. Adjust for your environment.
sox -V0 -t "$RECORD_FORMAT" -r "$RECORD_SRATE" -c "$RECORD_CHANNELS" -b "$RECORD_BITS" \
--input-buffer 8192 \
-d "$SOX_VAD_OUTPUT" \
vad 0.2s 0.5s 6% 0.1s 2>&1 | grep -v 'Input file' | grep -v 'Output file'
echo " Recording saved to: $SOX_VAD_OUTPUT"
echo ""
# --- Method 3: Python with Pyaudio and WebRTC VAD ---
# This is a highly robust and configurable method.
# WebRTC VAD is Google's voice activity detection library, known for accuracy.
# Pyaudio provides cross-platform audio input/output.
# This script will buffer audio and only save segments identified as speech.
echo "### METHOD 3: Python (Pyaudio + WebRTC VAD) ###"
echo " - Uses Google's WebRTC VAD for accurate speech detection."
echo " - Speak a phrase, then be silent for a moment (around 1-2 seconds)."
echo " - The script will automatically stop after detecting silence."
echo " - Press Ctrl+C if you want to stop early."
echo ""
PYTHON_VAD_OUTPUT="$OUTPUT_DIR/python_webrtcvad_$(date +%Y%m%d_%H%M%S).wav"
cat << EOF > "$OUTPUT_DIR/python_webrtcvad_script.py"
import pyaudio
import webrtcvad
import collections
import sys
import wave
import os
# Configuration
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK_SIZE = int(RATE / 100) # 10ms frames, required by WebRTC VAD
VAD_AGGRESSIVENESS = 3 # 0 (least aggressive) to 3 (most aggressive)
SILENCE_LIMIT_MS = 1500 # How many milliseconds of silence to consider end of speech
PRE_SPEECH_BUFFER_MS = 500 # How much audio to keep before speech starts
# Main recording logic
def record_and_vad(output_filename):
print(" (Listening for speech... Say something to start recording)")
audio = pyaudio.PyAudio()
# Try to find default input device
input_device_index = None
try:
default_input = audio.get_default_input_device_info()
input_device_index = default_input['index']
print(f" Using default input device: {default_input['name']}")
except Exception as e:
print(f" Could not get default input device: {e}")
print(" Falling back to first available input device.")
for i in range(audio.get_device_count()):
info = audio.get_device_info_by_index(i)
if info['maxInputChannels'] > 0:
input_device_index = info['index']
print(f" Using device {info['name']} at index {input_device_index}")
break
if input_device_index is None:
print(" ERROR: No input audio device found. Exiting.")
return
try:
stream = audio.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK_SIZE,
input_device_index=input_device_index)
except Exception as e:
print(f" ERROR: Could not open audio stream: {e}")
print(" Ensure Termux has microphone permissions and 'libportaudio' is installed.")
print(" You might need to adjust CHANNELS/RATE if your device is unusual.")
return
vad = webrtcvad.Vad(VAD_AGGRESSIVENESS)
frames = collections.deque()
speech_frames = collections.deque()
in_speech = False
silence_frames_count = 0
try:
while True:
data = stream.read(CHUNK_SIZE, exception_on_overflow=False)
is_speech = vad.is_speech(data, RATE)
frames.append(data)
if not in_speech:
# Buffer non-speech frames before speech starts
while len(frames) > RATE * (PRE_SPEECH_BUFFER_MS / 1000.0) / CHUNK_SIZE:
frames.popleft()
if is_speech:
if not in_speech:
print(" (Speech detected, recording started!)")
in_speech = True
# Add buffered pre-speech frames to the recording
speech_frames.extend(frames)
frames.clear() # Clear buffer, we're now capturing directly
speech_frames.append(data)
silence_frames_count = 0
elif in_speech:
speech_frames.append(data)
silence_frames_count += 1
if silence_frames_count * CHUNK_SIZE / RATE * 1000 > SILENCE_LIMIT_MS:
print(" (Silence detected, recording stopped.)")
break
else: # Not in speech, and hasn't started yet
pass # Just keep buffering the pre-speech frames
except KeyboardInterrupt:
print("\n Recording interrupted by user.")
finally:
print(" Cleaning up...")
stream.stop_stream()
stream.close()
audio.terminate()
if speech_frames:
wf = wave.open(output_filename, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(list(speech_frames)))
wf.close()
print(f" Recording saved to: {output_filename}")
else:
print(" No speech detected or recorded.")
if __name__ == "__main__":
record_and_vad(sys.argv[1])
EOF
python "$OUTPUT_DIR/python_webrtcvad_script.py" "$PYTHON_VAD_OUTPUT"
rm "$OUTPUT_DIR/python_webrtcvad_script.py" # Clean up temp script
echo ""
# --- Method 4: Python with SpeechRecognition Library (High-Level) ---
# This library provides a high-level interface to various STT engines,
# and its `listen()` method includes built-in VAD/silence detection.
# It's good for quick prototyping with online STT services.
echo "### METHOD 4: Python (SpeechRecognition Library) ###"
echo " - High-level, handles VAD/silence detection internally."
echo " - Speak a phrase, then be silent for a moment."
echo " - The script will automatically stop after detecting silence."
echo " - Note: This might not be as finely controllable as WebRTC VAD."
echo ""
PYTHON_SR_OUTPUT="$OUTPUT_DIR/python_speech_rec_$(date +%Y%m%d_%H%M%S).wav"
cat << EOF > "$OUTPUT_DIR/python_speech_rec_script.py"
import speech_recognition as sr
import os
import time
r = sr.Recognizer()
# Adjust for ambient noise once before starting to listen
# with sr.Microphone() as source:
# print(" Adjusting for ambient noise... Please wait...")
# r.adjust_for_ambient_noise(source, duration=1) # listen for 1 second to calibrate
# print(" Calibration complete.")
print(" (Listening for speech... Say something!)")
with sr.Microphone(sample_rate=16000) as source:
try:
# listen() blocks until speech is detected and then silence follows.
# phrase_time_limit: Max duration of a phrase.
# pause_threshold: How long silence (in seconds) to consider the end of a phrase.
audio = r.listen(source, phrase_time_limit=10, pause_threshold=1.5)
print(" (Speech recorded!)")
# Save the audio data to a WAV file
with open("$PYTHON_SR_OUTPUT", "wb") as f:
f.write(audio.get_wav_data())
print(f" Recording saved to: $PYTHON_SR_OUTPUT")
# Optional: Attempt STT with Google Web Speech API (requires internet)
# print(" Attempting STT via Google Web Speech API...")
# try:
# text = r.recognize_google(audio)
# print(f" You said: \"{text}\"")
# except sr.UnknownValueError:
# print(" Google Web Speech API could not understand audio")
# except sr.RequestError as e:
# print(f" Could not request results from Google Web Speech API service; {e}")
except sr.WaitTimeoutError:
print(" No speech detected within the timeout period.")
except Exception as e:
print(f" An error occurred during recording: {e}")
print(" Ensure Termux has microphone permissions.")
EOF
python "$OUTPUT_DIR/python_speech_rec_script.py"
rm "$OUTPUT_DIR/python_speech_rec_script.py" # Clean up temp script
echo ""
echo "---------------------------------------------------"
echo "All test methods completed. Check '$OUTPUT_DIR' for recordings."
echo "To listen to recordings, use 'play <filename>' with sox."
echo "e.g., play $SOX_OUTPUT"
echo "Remember to delete recordings to free up space: rm -r $OUTPUT_DIR"
echo "---------------------------------------------------"
How to Run the Script
- Save the code above as
voice_assistant_methods.sh in your Termux home directory (/data/data/com.termux/files/home/).
- Make it executable:
chmod +x voice_assistant_methods.sh
- Run it:
./voice_assistant_methods.sh
Explanation of Methods
-
SoX with Silence Detection (silence effect):
- Pros: Lightweight, pre-installed with
sox, effective for basic start/stop.
- Cons: Can be sensitive to background noise if not configured carefully.
silence specifically detects lack of sound above a threshold, which is not strictly VAD. It might cut off speech if you pause too long within a sentence.
- How it works: It monitors the input audio. Once the volume drops below a certain
threshold_final_volume for final_duration, it stops recording. The initial_duration and threshold_initial_volume are for the very beginning (e.g., if you run it and there's no sound, it'll stop immediately).
-
SoX with VAD (vad effect):
- Pros: More sophisticated than simple silence detection, designed specifically for speech. Still lightweight and pre-installed.
- Cons: Still requires careful tuning of parameters (
attack_duration, decay_duration, threshold) for optimal performance in different environments.
- How it works:
vad intelligently analyzes the characteristics of the audio to determine if speech is present. It has parameters to control how long speech must be continuous to be considered "active," and how long silence must last before it considers speech to have ended.
-
Python with Pyaudio and WebRTC VAD:
- Pros: Highly recommended for robust voice assistants. WebRTC VAD is Google's battle-tested voice activity detection library, known for its accuracy in various noisy environments. Python offers fine-grained control over the recording process, allowing for buffering, pre-speech retention, and custom logic.
- Cons: Requires Python and specific libraries (
pyaudio, webrtcvad). Pyaudio can sometimes be tricky to set up with Termux's audio backend.
- How it works:
- It continuously reads small chunks (
CHUNK_SIZE) of audio.
webrtcvad.Vad(aggressiveness) classifies each chunk as speech or non-speech.
- It maintains a buffer of recent frames.
- When speech is detected, it starts saving. It also prepends a small
PRE_SPEECH_BUFFER_MS of audio to capture the beginning of the word.
Next Steps for a Real Voice Assistant
Once you have the audio segment containing just the speech, you'll need to send it to a Speech-to-Text (STT) engine.
For STT:
-
Online STT (Recommended for accuracy, requires internet):
- Google Speech-to-Text API: The
SpeechRecognition library can easily use this (uncomment the relevant lines in Method 4).
- AssemblyAI, OpenAI Whisper API, etc.: You'd send your recorded WAV file to their APIs.
-
Offline STT (Recommended for privacy/latency, larger local install):
- Vosk-API: Excellent open-source offline STT. You can use their Python bindings.
pip install vosk
- Download a Vosk model (e.g.,
vosk-model-en-us-0.22) and place it locally.
- Whisper.cpp (or Python Whisper): OpenAI's Whisper model is state-of-the-art.
whisper.cpp is a C++ port that runs well on mobile/lower-end hardware. You'd need to compile it or find pre-compiled binaries for Termux, then use it via a subprocess call from Python.
Integration into a Loop:
For a real voice assistant, you'd wrap one of these methods (e.g., Method 3 or 4) in a continuous loop:
# Pseudo-code for a continuous assistant loop
while True:
print("Waiting for your command...")
audio_data = record_speech_segment() # Call one of your VAD/recording functions
if audio_data:
text = perform_stt(audio_data)
if text:
print(f"You said: {text}")
react_to_command(text)
else:
print("Could not understand audio.")
time.sleep(0.1) # Small delay to prevent busy-waiting
This comprehensive script and explanation should give you a solid foundation for building an intelligent voice assistant in Termux!