Here's a comprehensive test script that explores multiple methods for real-time voice activity detection in Termux:
#!/data/data/com.termux/files/usr/bin/bash
# Voice Activity Detection Test Script for Termux
# Tests multiple methods for real-time speech detection
echo "=== Voice Assistant VAD Test Suite ==="
echo "Testing multiple methods for voice activity detection..."
# Install required packages
install_deps() {
echo -e "\n[*] Installing dependencies..."
pkg update -y
pkg install -y sox python ffmpeg pulseaudio alsa-utils termux-api
pip install pyaudio sounddevice numpy scipy webrtcvad speech_recognition pydub
}
# Method 1: Sox with silence detection
test_sox_vad() {
echo -e "\n[Method 1] Testing SOX silence detection..."
cat > test_sox_vad.sh << 'EOF'
#!/bin/bash
while true; do
echo "Listening... (speak now)"
# Record until 1s of silence after sound
sox -d -t wav - silence 1 0.1 1% 1 1.0 1% | \
sox - recording.wav
size=$(stat -c%s recording.wav 2>/dev/null || echo 0)
if [ "$size" -gt 1000 ]; then
echo "Speech detected! Size: $size bytes"
# Process with STT here
fi
done
EOF
chmod +x test_sox_vad.sh
timeout 10s ./test_sox_vad.sh || echo "Sox test completed"
}
# Method 2: Python with pyaudio and energy-based VAD
test_pyaudio_vad() {
echo -e "\n[Method 2] Testing PyAudio energy-based VAD..."
cat > test_pyaudio_vad.py << 'EOF'
import pyaudio
import numpy as np
import wave
import time
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
THRESHOLD = 1000 # Energy threshold
SILENCE_LIMIT = 1.0 # Seconds of silence before stopping
p = pyaudio.PyAudio()
def is_silent(data_chunk):
"""Returns 'True' if below the 'silent' threshold"""
return np.sqrt(np.mean(np.square(np.frombuffer(data_chunk, dtype=np.int16)))) < THRESHOLD
def record_until_silence():
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE,
input=True, frames_per_buffer=CHUNK)
print("Listening for speech...")
frames = []
current_silence_time = 0
recording = False
while True:
data = stream.read(CHUNK)
frames.append(data)
silent = is_silent(data)
if not silent and not recording:
print("Speech started!")
recording = True
current_silence_time = 0
elif silent and recording:
current_silence_time += CHUNK / RATE
if current_silence_time > SILENCE_LIMIT:
print("Speech ended!")
break
elif not silent:
current_silence_time = 0
stream.stop_stream()
stream.close()
# Save recording
if frames:
wf = wave.open('pyaudio_recording.wav', 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
print(f"Saved {len(frames)} frames")
try:
for i in range(3):
record_until_silence()
time.sleep(0.5)
except Exception as e:
print(f"PyAudio error: {e}")
finally:
p.terminate()
EOF
timeout 15s python test_pyaudio_vad.py || echo "PyAudio test completed"
}
# Method 3: WebRTC VAD (Google's VAD)
test_webrtc_vad() {
echo -e "\n[Method 3] Testing WebRTC VAD..."
cat > test_webrtc_vad.py << 'EOF'
import webrtcvad
import pyaudio
import collections
import sys
vad = webrtcvad.Vad(2) # Aggressiveness level (0-3)
CHUNK_DURATION_MS = 30 # ms
RATE = 16000
CHUNK = int(RATE * CHUNK_DURATION_MS / 1000)
FORMAT = pyaudio.paInt16
CHANNELS = 1
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE,
input=True, frames_per_buffer=CHUNK)
print("WebRTC VAD listening...")
frames = []
voiced_frames = collections.deque(maxlen=10)
triggered = False
try:
for _ in range(500): # Process 500 chunks
frame = stream.read(CHUNK)
is_speech = vad.is_speech(frame, RATE)
if is_speech:
if not triggered:
print("Speech detected!")
triggered = True
frames.append(frame)
else:
if triggered and len(frames) > 10:
print("Speech ended, saving...")
# Save frames here
frames = []
triggered = False
sys.stdout.write('1' if is_speech else '0')
sys.stdout.flush()
except Exception as e:
print(f"\nWebRTC error: {e}")
finally:
stream.stop_stream()
stream.close()
p.terminate()
EOF
timeout 10s python test_webrtc_vad.py || echo -e "\nWebRTC test completed"
}
# Method 4: Speech Recognition with ambient noise adjustment
test_speech_recognition() {
echo -e "\n[Method 4] Testing speech_recognition library..."
cat > test_speech_recognition.py << 'EOF'
import speech_recognition as sr
import time
r = sr.Recognizer()
r.energy_threshold = 300 # Minimum audio energy to consider for recording
r.dynamic_energy_threshold = True
r.pause_threshold = 0.8 # Seconds of silence before phrase is considered complete
with sr.Microphone() as source:
print("Adjusting for ambient noise...")
r.adjust_for_ambient_noise(source, duration=1)
print(f"Energy threshold: {r.energy_threshold}")
print("Listening for speech...")
try:
for i in range(3):
print(f"\nRound {i+1}: Speak now...")
audio = r.listen(source, timeout=5, phrase_time_limit=10)
print(f"Got audio! Duration: {len(audio.frame_data) / audio.sample_rate / audio.sample_width:.2f}s")
# Save audio
with open(f"speech_rec_{i}.wav", "wb") as f:
f.write(audio.get_wav_data())
except sr.WaitTimeoutError:
print("No speech detected")
except Exception as e:
print(f"Error: {e}")
EOF
timeout 20s python test_speech_recognition.py || echo "Speech recognition test completed"
}
# Method 5: Continuous monitoring with threshold detection
test_continuous_monitor() {
echo -e "\n[Method 5] Testing continuous monitoring..."
cat > test_continuous.py << 'EOF'
import sounddevice as sd
import numpy as np
import queue
import threading
import time
q = queue.Queue()
recording = []
is_recording = False
silence_counter = 0
def callback(indata, frames, time, status):
global is_recording, silence_counter, recording
if status:
print(status)
volume = np.sqrt(np.mean(indata**2))
q.put(volume)
if volume > 0.01: # Threshold
if not is_recording:
print("\n🎤 Recording started!")
is_recording = True
silence_counter = 0
recording.extend(indata.copy())
elif is_recording:
silence_counter += 1
recording.extend(indata.copy())
if silence_counter > 30: # ~1 second of silence
print("🛑 Recording stopped!")
# Process recording here
print(f"Recorded {len(recording)} samples")
recording = []
is_recording = False
silence_counter = 0
print("Continuous monitoring started...")
with sd.InputStream(callback=callback, channels=1, samplerate=16000):
try:
for _ in range(100):
vol = q.get()
bars = int(vol * 100)
print(f"\r{'█' * bars:<50} {vol:.4f}", end='')
time.sleep(0.1)
except KeyboardInterrupt:
print("\nStopped")
EOF
timeout 15s python test_continuous.py || echo -e "\nContinuous monitoring test completed"
}
# Method 6: Termux-API microphone with chunked reading
test_termux_api_chunked() {
echo -e "\n[Method 6] Testing Termux-API chunked approach..."
cat > test_termux_chunked.sh << 'EOF'
#!/bin/bash
# Start recording in background
termux-microphone-record -f recording.wav &
PID=$!
echo "Recording started, monitoring size..."
last_size=0
silent_iterations=0
while kill -0 $PID 2>/dev/null; do
sleep 0.1
current_size=$(stat -c%s recording.wav 2>/dev/null || echo 0)
if [ "$current_size" -gt "$last_size" ]; then
echo -ne "\rRecording: $current_size bytes"
silent_iterations=0
else
silent_iterations=$((silent_iterations + 1))
if [ "$silent_iterations" -gt 10 ]; then
echo -e "\nSilence detected, stopping..."
termux-microphone-record -q
break
fi
fi
last_size=$current_size
done
echo "Recording complete!"
EOF
chmod +x test_termux_chunked.sh
timeout 10s ./test_termux_chunked.sh || echo "Termux chunked test completed"
}
# Main execution
main() {
echo -e "\nSelect tests to run:"
echo "1) Install dependencies only"
echo "2) Test all methods"
echo "3) Sox VAD"
echo "4) PyAudio energy-based"
echo "5) WebRTC VAD"
echo "6) Speech Recognition lib"
echo "7) Continuous monitoring"
echo "8) Termux-API chunked"
read -p "Enter choice (1-8): " choice
case $choice in
1) install_deps ;;
2)
install_deps
test_sox_vad
test_pyaudio_vad
test_webrtc_vad
test_speech_recognition
test_continuous_monitor
test_termux_api_chunked
;;
3) test_sox_vad ;;
4) test_pyaudio_vad ;;
5) test_webrtc_vad ;;
6) test_speech_recognition ;;
7) test_continuous_monitor ;;
8) test_termux_api_chunked ;;
*) echo "Invalid choice" ;;
esac
echo -e "\n=== Test Summary ==="
echo "Check the generated files:"
ls -la *.wav *.py *.sh 2>/dev/null | grep -E "\.(wav|py|sh)$"
}
main
This test script explores 6 different methods:
- Sox with silence detection - Uses Sox's built-in silence detection to start/stop recording
- PyAudio with energy-based VAD - Monitors audio energy levels to detect speech
- WebRTC VAD - Google's robust voice activity detection algorithm
- Speech Recognition library - Built-in VAD with ambient noise adjustment
- Continuous monitoring - Real-time volume monitoring with sounddevice
- Termux-API chunked - Modified approach to termux-microphone-record
Each method has different advantages:
- Sox is lightweight and works well for simple cases
- WebRTC VAD is very accurate and handles noise well
- Speech Recognition library has built-in STT integration
- Continuous monitoring gives real-time feedback
Run the script and test each method to see which works best for your environment and use case. The most promising for a voice assistant would likely be methods 3 (WebRTC) or 4 (Speech Recognition) as they're specifically designed for speech detection.