Skip to content

Weather App with Voice Commands

Abstract

Build a Weather App that fetches weather information based on voice commands. The app uses speech recognition to capture user queries and displays weather data from an API. This project demonstrates API integration, speech recognition, and GUI development in Python.

Prerequisites

  • Python 3.6 or above
  • Text Editor or IDE
  • Basic understanding of Python syntax
  • Familiarity with Tkinter for GUI development
  • Knowledge of speech recognition and API requests

Getting Started

Creating a new project

  1. Create a new project folder and name it weather_app_with_voice_commandsweather_app_with_voice_commands.
  2. Create a new file inside the folder and name it weather_app_with_voice_commands.pyweather_app_with_voice_commands.py.
  3. Open the project folder in your favorite text editor or IDE.
  4. Copy the code below and paste it into the weather_app_with_voice_commands.pyweather_app_with_voice_commands.py file.

Write the code

⚙️ weather_app_with_voice_commands.py
weather_app_with_voice_commands.py
"""
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.py
"""
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()
 

Key Features

  • Voice recognition to capture city names
  • Fetch weather data from an API
  • Display weather information in a user-friendly format
  • GUI interface for user interaction

Explanation

Speech Recognition

The app uses the speech_recognitionspeech_recognition library to capture voice input:

weather_app_with_voice_commands.py
recognizer = sr.Recognizer()
with sr.Microphone() as source:
    audio = recognizer.listen(source)
    city = recognizer.recognize_google(audio)
weather_app_with_voice_commands.py
recognizer = sr.Recognizer()
with sr.Microphone() as source:
    audio = recognizer.listen(source)
    city = recognizer.recognize_google(audio)

Fetching Weather Data

Weather data is fetched from the OpenWeatherMap API:

weather_app_with_voice_commands.py
params = {"q": city, "appid": API_KEY, "units": "metric"}
response = requests.get(BASE_URL, params=params)
weather_app_with_voice_commands.py
params = {"q": city, "appid": API_KEY, "units": "metric"}
response = requests.get(BASE_URL, params=params)

Displaying Results

Weather information is shown in a Tkinter Label widget:

weather_app_with_voice_commands.py
self.result_label.config(text=f"Weather: {weather}\nTemperature: {temp}°C")
weather_app_with_voice_commands.py
self.result_label.config(text=f"Weather: {weather}\nTemperature: {temp}°C")

Running the Application

  1. Save the file.
  2. Install required dependencies:
pip install speechrecognition requests
pip install speechrecognition requests
  1. Run the application:
python weather_app_with_voice_commands.py
python weather_app_with_voice_commands.py

Conclusion

This Weather App with Voice Commands project is a great way to learn about API integration and speech recognition in Python. You can extend it by adding support for more languages, weather forecasts, or voice feedback.

Was this page helpful?

Let us know how we did