Certainly! Below is a Python script that implements the functionalities you've described. This script allows the user to select a microphone, monitors the audio amplitude, listens for the keyword "Alfred," fetches images from Unsplash based on subsequent voice commands, and displays them with animations.
Prerequisites
Before running the script, make sure you have the following Python libraries installed:
pyaudio (for audio input)
numpy (for audio processing)
speechrecognition (for voice recognition)
requests (for HTTP requests to Unsplash API)
Pillow (for image handling)
pygame (for displaying images and animations)
You can install them using pip:
pip install pyaudio numpy SpeechRecognition requests Pillow pygame
Note: pyaudio might require additional setup depending on your operating system.
Script Overview
The script performs the following steps:
- Microphone Setup: Lists available microphones and lets the user select one.
- Amplitude Detection: Continuously monitors the audio amplitude to detect when to start listening.
- Voice Command Recognition: Uses speech recognition to detect the keyword "Alfred" and subsequent commands.
- Image Fetching: Fetches images from Unsplash based on the voice command.
- Display Images: Shows the images on a green screen with sliding animation.
- Continuous Listening: Continues to listen for new commands after "Alfred" is recognized.
- Exit and Reset Logic: Resets the listening state based on audio amplitude thresholds.
The Code
import pyaudio
import numpy as np
import speech_recognition as sr
import threading
import requests
import io
from PIL import Image
import pygame
import sys
import time
# ---------------------
# Configuration Section
# ---------------------
# Audio configuration
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
AMPLITUDE_THRESHOLD = 500 # Adjust this value based on testing
# Listening state
listening = False
keyword_detected = False
last_sound_time = time.time()
# Unsplash API configuration
UNSPLASH_ACCESS_KEY = 'YOUR_UNSPLASH_ACCESS_KEY' # Replace with your Unsplash Access Key
UNSPLASH_URL = 'https://api.unsplash.com/photos/random'
# Pygame initialization for image display
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Voice Command Image Display')
# Green background
GREEN = (0, 255, 0)
screen.fill(GREEN)
pygame.display.flip()
# ---------------------
# Function Definitions
# ---------------------
def list_microphones():
"""Lists available microphone devices."""
p = pyaudio.PyAudio()
print("Available audio input devices:")
for i in range(p.get_device_count()):
info = p.get_device_info_by_index(i)
if info['maxInputChannels'] > 0:
print(f"Index {i}: {info['name']}")
p.terminate()
def select_microphone():
"""Allows the user to select a microphone by index."""
list_microphones()
device_index = int(input("Enter the index of the microphone you want to use: "))
return device_index
def monitor_audio(device_index):
"""Monitors audio amplitude and triggers listening when threshold is exceeded."""
global listening, last_sound_time
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
input_device_index=device_index,
frames_per_buffer=CHUNK)
print("Monitoring audio...")
try:
while True:
data = stream.read(CHUNK, exception_on_overflow=False)
amplitude = np.frombuffer(data, np.int16).astype(np.int)
max_amplitude = np.max(np.abs(amplitude))
if max_amplitude > AMPLITUDE_THRESHOLD:
last_sound_time = time.time()
if not listening:
print("Sound detected. Starting to listen...")
listening = True
threading.Thread(target=listen_for_commands, args=(device_index,)).start()
else:
if listening and (time.time() - last_sound_time) > 3:
print("No sound detected for a while. Stopping listening.")
listening = False
# Handle pygame events to keep the window responsive
for event in pygame.event.get():
if event.type == pygame.QUIT:
print("Exiting...")
stream.stop_stream()
stream.close()
p.terminate()
pygame.quit()
sys.exit()
except KeyboardInterrupt:
print("Interrupted by user.")
finally:
stream.stop_stream()
stream.close()
p.terminate()
def listen_for_commands(device_index):
"""Listens for voice commands and processes them."""
global keyword_detected, listening
r = sr.Recognizer()
with sr.Microphone(device_index=device_index, sample_rate=RATE, chunk_size=CHUNK) as source:
while listening:
print("Listening...")
try:
audio = r.listen(source, timeout=5, phrase_time_limit=5)
command = r.recognize_google(audio).lower()
print(f"Recognized command: {command}")
if "alfred" in command:
print("Keyword 'Alfred' detected.")
keyword_detected = True
continue # Wait for the next command
if keyword_detected:
# Process the command
search_term = command
print(f"Fetching images for '{search_term}'...")
images = fetch_images(search_term)
if images:
display_images(images)
else:
print("No images found.")
keyword_detected = False # Reset the keyword detection
except sr.WaitTimeoutError:
print("Listening timed out while waiting for phrase.")
listening = False
except sr.UnknownValueError:
print("Could not understand audio.")
except sr.RequestError as e:
print(f"Could not request results; {e}")
except Exception as e:
print(f"An error occurred: {e}")
def fetch_images(query):
"""Fetches images from Unsplash based on the query."""
headers = {'Accept-Version': 'v1', 'Authorization': f'Client-ID {UNSPLASH_ACCESS_KEY}'}
params = {'query': query, 'count': 5} # Get 5 random images
try:
response = requests.get(UNSPLASH_URL, headers=headers, params=params)
response.raise_for_status()
data = response.json()
images = []
for item in data:
image_url = item['urls']['regular']
image_response = requests.get(image_url)
image_response.raise_for_status()
image_data = Image.open(io.BytesIO(image_response.content))
images.append(image_data)
return images
except requests.exceptions.HTTPError as errh:
print(f"Http Error: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
print(f"OOps: Something Else {err}")
return []
def display_images(images):
"""Displays images on the green screen with sliding animation."""
for img in images:
# Resize image to fit screen while maintaining aspect ratio
img = img.convert('RGBA')
img.thumbnail((SCREEN_WIDTH, SCREEN_HEIGHT))
mode = img.mode
size = img.size
data = img.tobytes()
image_surface = pygame.image.fromstring(data, size, mode)
# Animation: Slide in from the right
x = SCREEN_WIDTH
y = (SCREEN_HEIGHT - img.height) // 2
while x > (SCREEN_WIDTH - img.width) // 2:
x -= 10 # Adjust the speed of the slide
screen.fill(GREEN)
screen.blit(image_surface, (x, y))
pygame.display.update()
pygame.time.delay(10)
# Display the image for a few seconds
pygame.time.delay(2000)
def main():
device_index = select_microphone()
monitor_audio(device_index)
if __name__ == '__main__':
main()
Instructions
-
Insert Unsplash Access Key: Replace 'YOUR_UNSPLASH_ACCESS_KEY' with your actual Unsplash Access Key. You can obtain one by registering as a developer on Unsplash.
-
Run the Script: Execute the script in your Python environment.
-
Select Microphone: When prompted, enter the index of the microphone you wish to use.
-
Interact with the Script:
- Make a noise or speak to exceed the amplitude threshold.
- Say "Alfred" clearly to trigger the listening for commands.
- After "Alfred" is detected, say a keyword or phrase for the image search.
- Watch as images related to your search are displayed with animations.
-
Exit: You can stop the script by closing the window or pressing Ctrl+C in the terminal.
Notes
-
Adjusting the Amplitude Threshold: The AMPLITUDE_THRESHOLD variable might need tweaking based on your microphone sensitivity and ambient noise levels.
-
Error Handling: The script includes basic error handling. In real-world applications, you'd want to handle exceptions more gracefully.
-
Speech Recognition Accuracy: The accuracy of the speech_recognition library depends on the quality of the microphone and ambient noise. Consider using a better microphone or a quieter environment for improved results.
-
Unsplash API Limits: Unsplash imposes rate limits on the API. Ensure you comply with their usage policies.
-
Extensibility: This script serves as a basic implementation. You can extend it by adding features like handling multiple keywords, more advanced animations, or integrating with other services.
Disclaimer
Be mindful of the resources used by the script, such as network bandwidth and API rate limits. Always ensure you have the rights and permissions for any content retrieved and displayed.