Certainly! Below is a Python script that integrates voice commands with OBS (Open Broadcaster Software) via WebSocket to manage the display of images and interact with the Unsplash API. This script listens for specific voice commands, slides images onto the screen in OBS, and fetches images from Unsplash based on spoken keywords.
Prerequisites:
- OBS Studio installed on your computer.
- OBS WebSocket Plugin installed and configured in OBS.
- Python 3.x installed on your computer.
- Access to the Unsplash API (you'll need an access key).
- Microphone connected to your computer for voice commands.
Install Required Python Libraries:
pip install speechrecognition obs-websocket-py requests pynput
Python Script:
import speech_recognition as sr
import obswebsocket
import obswebsocket.requests
import requests
import logging
import os
import time
# Configure logging
logging.basicConfig(level=logging.INFO)
# OBS WebSocket settings
OBS_HOST = 'localhost'
OBS_PORT = 4444 # Default port for OBS WebSocket
OBS_PASSWORD = 'your_obs_password' # Replace with your OBS WebSocket password
# Unsplash API settings
UNSPLASH_ACCESS_KEY = 'your_unsplash_access_key' # Replace with your Unsplash API access key
UNSPLASH_URL = 'https://api.unsplash.com/photos/random'
# Paths to images
SEARCH_IMAGE_PATH = 'C:/path/to/your/search_image.jpg' # Replace with your path
YAY_IMAGE_PATH = 'C:/path/to/your/yay_image.png' # Replace with your path
def connect_to_obs():
try:
client = obswebsocket.obsws(OBS_HOST, OBS_PORT, OBS_PASSWORD)
client.connect()
logging.info("Connected to OBS WebSocket.")
return client
except Exception as e:
logging.error(f"Failed to connect to OBS: {e}")
return None
def slide_in_image(client, source_name, position):
try:
client.call(obswebsocket.requests.SetSceneItemProperties(
item=source_name,
position=position,
bounds={'x': 0, 'y': 0},
bounds_align=0,
scale={'x': 1.0, 'y': 1.0},
visible=True
))
logging.info(f"Slid in image: {source_name}")
except Exception as e:
logging.error(f"Error sliding in {source_name}: {e}")
def slide_both_images_in(client):
slide_in_image(client, 'SearchImage', {'x': 100, 'y': 100})
slide_in_image(client, 'YayImage', {'x': 500, 'y': 100})
def listen_for_command(prompt):
recognizer = sr.Recognizer()
microphone = sr.Microphone()
logging.info(prompt)
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
try:
command = recognizer.recognize_google(audio)
logging.info(f"Heard command: {command}")
return command.lower()
except sr.UnknownValueError:
logging.warning("Could not understand audio.")
return ""
except sr.RequestError as e:
logging.error(f"Could not request results; {e}")
return ""
def download_image_from_unsplash(keywords):
params = {
'query': keywords,
'client_id': UNSPLASH_ACCESS_KEY,
'orientation': 'landscape'
}
response = requests.get(UNSPLASH_URL, params=params)
if response.status_code == 200:
data = response.json()
image_url = data['urls']['regular']
image_response = requests.get(image_url)
with open(SEARCH_IMAGE_PATH, 'wb') as f:
f.write(image_response.content)
logging.info(f"Downloaded image for '{keywords}' from Unsplash.")
else:
logging.error(f"Error fetching from Unsplash: Status code {response.status_code}")
def main():
client = connect_to_obs()
if not client:
return
try:
# Wait for the activation command
command = listen_for_command("Say 'Alfred' to activate.")
if 'alfred' in command:
slide_both_images_in(client)
time.sleep(1) # Wait for images to slide in
# Wait for the second command
command = listen_for_command("Listening for your search command.")
if 'me a' in command:
# Extract keywords after 'me a'
keywords = command.split('me a', 1)[1].strip()
logging.info(f"Extracted keywords: {keywords}")
if keywords:
# Download image from Unsplash
download_image_from_unsplash(keywords)
# Refresh the image source in OBS
client.call(obswebsocket.requests.SetSourceSettings(
sourceName='SearchImage',
sourceSettings={'file': SEARCH_IMAGE_PATH}
))
logging.info("Updated image in OBS.")
else:
logging.warning("No keywords provided after 'me a'.")
else:
logging.warning("Second command did not contain 'me a'.")
else:
logging.info("Activation command 'Alfred' not detected.")
except Exception as e:
logging.error(f"An error occurred: {e}")
finally:
client.disconnect()
logging.info("Disconnected from OBS.")
if __name__ == '__main__':
main()
Instructions to Use the Script:
-
Configure OBS:
- Ensure OBS Studio is running.
- Install the OBS WebSocket plugin and configure it with a password.
- Create a scene with two image sources named
'SearchImage' and 'YayImage'.
- Set initial positions for these images off-screen if you want them to slide in.
-
Update Script Variables:
- Replace
'your_obs_password' with your OBS WebSocket password.
- Replace
'your_unsplash_access_key' with your Unsplash API access key.
- Update
'C:/path/to/your/search_image.jpg' and 'C:/path/to/your/yay_image.png' with the actual file paths on your computer.
-
Run the Script:
- Ensure your microphone is set up and working.
- Run the script from the command line or an IDE.
- Speak "Alfred" to trigger the image sliding.
- After the images have slid in, say a phrase that includes "me a" followed by the keywords for the image you want to search, such as "Show me a beautiful sunset."
-
Troubleshooting:
- If the script doesn't recognize your voice commands, ensure your microphone is properly configured and working.
- Check that the OBS WebSocket connection details are correct.
- Verify that the source names in OBS match those in the script.
- Ensure you have proper access to the Unsplash API and are not exceeding rate limits.
Script Overview:
Notes:
- Ensure you comply with Unsplash's API Guidelines. Do not use the API for high-volume requests or without proper attribution if required.
- The
speech_recognition library may require an internet connection to access Google's speech recognition API.
- If you encounter issues with the microphone or audio, consider testing with a different input device or checking system audio settings.
- The script includes basic error handling; you can expand on this to handle specific exceptions as needed.
Disclaimer:
- This script is provided as a sample and may need adjustments for your specific setup.
- Always secure your API keys and passwords; consider using environment variables or a separate configuration file to store sensitive information.
- Test the script thoroughly before using it in a live environment.
Let me know if you need any further assistance or modifications to the script!