Skip to content

Weather App with Voice Commands

Abstract

Weather App with Voice Commands is a Python project that fetches weather data and allows users to interact using voice commands. It demonstrates API integration, speech recognition, and GUI development. This project is ideal for learning about voice interfaces, REST APIs, and real-world automation.

Prerequisites

  • Python 3.6 or above
  • requests (pip install requestspip install requests)
  • speech_recognition (pip install SpeechRecognitionpip install SpeechRecognition)
  • tkinter (usually pre-installed)

Before you Start

Install Python, requests, and SpeechRecognition. Obtain a free API key from a weather service (e.g., OpenWeatherMap).

Getting Started

  1. Create a folder named weather-voice-appweather-voice-app.
  2. Create a file named weather_app_with_voice_commands.pyweather_app_with_voice_commands.py.
  3. Copy the code below into your file.
⚙️ Weather App with Voice Commands
Weather App with Voice Commands
"""
Weather App with Voice Commands
 
A Python application that fetches weather information based on voice commands. Features include:
- Voice recognition to capture user queries.
- Fetching weather data from an API.
- Displaying weather information in a user-friendly format.
"""
 
import speech_recognition as sr
import requests
from tkinter import Tk, Label, Button, messagebox
 
API_KEY = "your_openweathermap_api_key"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
 
 
class WeatherApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Weather App with Voice Commands")
 
        self.label = Label(root, text="Click the button and say a city name:")
        self.label.pack(pady=10)
 
        self.voice_button = Button(root, text="Speak", command=self.get_weather_by_voice)
        self.voice_button.pack(pady=5)
 
        self.result_label = Label(root, text="", wraplength=400, justify="left")
        self.result_label.pack(pady=10)
 
    def get_weather_by_voice(self):
        """Capture voice input and fetch weather information."""
        recognizer = sr.Recognizer()
        with sr.Microphone() as source:
            try:
                self.label.config(text="Listening...")
                audio = recognizer.listen(source)
                city = recognizer.recognize_google(audio)
                self.label.config(text=f"You said: {city}")
                self.fetch_weather(city)
            except sr.UnknownValueError:
                messagebox.showerror("Error", "Sorry, I could not understand the audio.")
            except sr.RequestError:
                messagebox.showerror("Error", "Could not request results, please check your internet connection.")
 
    def fetch_weather(self, city):
        """Fetch weather data from the OpenWeatherMap API."""
        params = {"q": city, "appid": API_KEY, "units": "metric"}
        try:
            response = requests.get(BASE_URL, params=params)
            data = response.json()
 
            if response.status_code == 200:
                weather = data["weather"][0]["description"].capitalize()
                temp = data["main"]["temp"]
                feels_like = data["main"]["feels_like"]
                humidity = data["main"]["humidity"]
 
                result = (
                    f"Weather in {city}:\n"
                    f"Condition: {weather}\n"
                    f"Temperature: {temp}°C\n"
                    f"Feels Like: {feels_like}°C\n"
                    f"Humidity: {humidity}%"
                )
                self.result_label.config(text=result)
            else:
                messagebox.showerror("Error", data.get("message", "Failed to fetch weather data."))
        except Exception as e:
            messagebox.showerror("Error", f"An error occurred: {e}")
 
 
def main():
    root = Tk()
    app = WeatherApp(root)
    root.mainloop()
 
 
if __name__ == "__main__":
    main()
 
Weather App with Voice Commands
"""
Weather App with Voice Commands
 
A Python application that fetches weather information based on voice commands. Features include:
- Voice recognition to capture user queries.
- Fetching weather data from an API.
- Displaying weather information in a user-friendly format.
"""
 
import speech_recognition as sr
import requests
from tkinter import Tk, Label, Button, messagebox
 
API_KEY = "your_openweathermap_api_key"
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
 
 
class WeatherApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Weather App with Voice Commands")
 
        self.label = Label(root, text="Click the button and say a city name:")
        self.label.pack(pady=10)
 
        self.voice_button = Button(root, text="Speak", command=self.get_weather_by_voice)
        self.voice_button.pack(pady=5)
 
        self.result_label = Label(root, text="", wraplength=400, justify="left")
        self.result_label.pack(pady=10)
 
    def get_weather_by_voice(self):
        """Capture voice input and fetch weather information."""
        recognizer = sr.Recognizer()
        with sr.Microphone() as source:
            try:
                self.label.config(text="Listening...")
                audio = recognizer.listen(source)
                city = recognizer.recognize_google(audio)
                self.label.config(text=f"You said: {city}")
                self.fetch_weather(city)
            except sr.UnknownValueError:
                messagebox.showerror("Error", "Sorry, I could not understand the audio.")
            except sr.RequestError:
                messagebox.showerror("Error", "Could not request results, please check your internet connection.")
 
    def fetch_weather(self, city):
        """Fetch weather data from the OpenWeatherMap API."""
        params = {"q": city, "appid": API_KEY, "units": "metric"}
        try:
            response = requests.get(BASE_URL, params=params)
            data = response.json()
 
            if response.status_code == 200:
                weather = data["weather"][0]["description"].capitalize()
                temp = data["main"]["temp"]
                feels_like = data["main"]["feels_like"]
                humidity = data["main"]["humidity"]
 
                result = (
                    f"Weather in {city}:\n"
                    f"Condition: {weather}\n"
                    f"Temperature: {temp}°C\n"
                    f"Feels Like: {feels_like}°C\n"
                    f"Humidity: {humidity}%"
                )
                self.result_label.config(text=result)
            else:
                messagebox.showerror("Error", data.get("message", "Failed to fetch weather data."))
        except Exception as e:
            messagebox.showerror("Error", f"An error occurred: {e}")
 
 
def main():
    root = Tk()
    app = WeatherApp(root)
    root.mainloop()
 
 
if __name__ == "__main__":
    main()
 
  1. Run the script: python weather_app_with_voice_commands.pypython weather_app_with_voice_commands.py

Explanation

Code Breakdown

  1. Import modules
import requests
import speech_recognition as sr
import tkinter as tk
import requests
import speech_recognition as sr
import tkinter as tk
  1. Fetch weather and process voice
def get_weather(city):
    # Fetch weather data from API
    pass
 
def listen_for_command():
    # Use microphone to get user input
    pass
def get_weather(city):
    # Fetch weather data from API
    pass
 
def listen_for_command():
    # Use microphone to get user input
    pass
  1. GUI for weather display
root = tk.Tk()
root.title('Weather App with Voice Commands')
# ...setup widgets for weather info and voice input...
root.mainloop()
root = tk.Tk()
root.title('Weather App with Voice Commands')
# ...setup widgets for weather info and voice input...
root.mainloop()

Features

  • Fetches weather data from API
  • Accepts voice commands
  • GUI for display
  • Easy to extend for more features

How It Works

  • Listens for voice input
  • Fetches weather for requested city
  • Displays info in GUI

GUI Components

  • Label: Shows weather info
  • Button: Starts voice recognition
  • Entry box: For manual city input

Use Cases

  • Hands-free weather updates
  • Learn API and voice integration
  • Build smart home apps

Next Steps

You can enhance this project by:

  • Adding more voice commands
  • Supporting multiple languages
  • Improving GUI design
  • Integrating with other smart devices

Enhanced Version Ideas

def add_language_support():
    # Recognize commands in other languages
    pass
 
def integrate_with_smart_home():
    # Control devices based on weather
    pass
def add_language_support():
    # Recognize commands in other languages
    pass
 
def integrate_with_smart_home():
    # Control devices based on weather
    pass

Troubleshooting Tips

  • API key errors: Check your key
  • Voice not recognized: Check microphone
  • GUI not showing: Ensure Tkinter is installed

Conclusion

This project teaches API usage, speech recognition, and GUI basics. Extend it for more features and smart automation.

Was this page helpful?

Let us know how we did