File size: 3,298 Bytes
ed9b1d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import speech_recognition as sr  # type: ignore
import os
import pygame  # type: ignore
from gtts import gTTS  # type: ignore
from pydub import AudioSegment
from pydub.playback import play

# Dog sound files (Ensure these files exist)
dog_sounds = {
    "sit": r'C:\Users\User\Downloads\dog_sit.mp3',
    "come": r'C:\Users\User\Downloads\dog_come.mp3',
    "fetch": r'C:\Users\User\Downloads\dog_fetch.mp3',
    "treat": r'C:\Users\User\Downloads\dog_treat.mp3',
    "play": r'C:\Users\User\Downloads\dog_play.mp3',
    "bark": r'C:\Users\User\Downloads\dog_bark.mp3'
}

# Initialize speech recognizer
recognizer = sr.Recognizer()

# Initialize pygame mixer
pygame.mixer.init()


def recognize_speech():
    """Recognizes speech from the microphone input."""
    with sr.Microphone() as source:
        print("Listening for command...")
        try:
            audio = recognizer.listen(source, timeout=5)
            command = recognizer.recognize_google(audio)
            print(f"Human said: {command}")
            return command.lower()
        except sr.UnknownValueError:
            print("Sorry, I could not understand your speech.")
            return None
        except sr.RequestError:
            print("Sorry, the speech service is unavailable.")
            return None
        except sr.WaitTimeoutError:
            print("No speech detected. Please try again.")
            return None


def dog_response(command):
    """Plays the corresponding dog sound based on the recognized command."""
    if command:
        # Check if command matches known keywords
        for key in dog_sounds:
            if key in command:
                play_dog_sound(dog_sounds[key])
                return
        
        # Default to bark sound if command is unknown
        print("No specific dog command recognized. Playing default bark sound.")
        play_dog_sound(dog_sounds["bark"])
    else:
        print("No command to process.")


def play_dog_sound(sound_file):
    """Plays an audio file using Pygame."""
    if os.path.exists(sound_file):
        pygame.mixer.music.load(sound_file)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():  # Wait until sound finishes playing
            continue
    else:
        print(f"Error: Sound file '{sound_file}' not found.")


def make_dog_response(text):
    """Generates a playful dog response using text-to-speech."""
    try:
        tts = gTTS(text=text, lang='en')
        response_file = "dog_response.mp3"
        tts.save(response_file)
        
        pygame.mixer.music.load(response_file)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            continue

        os.remove(response_file)  # Clean up the temporary file
    except Exception as e:
        print(f"Error generating speech: {e}")


def main():
    """Main loop to listen for speech commands and respond accordingly."""
    print("Say 'exit' or 'quit' to stop.")
    while True:
        command = recognize_speech()
        if command in ["exit", "quit"]:
            print("Exiting program. Goodbye!")
            break

        dog_response(command)  # Process command
        make_dog_response(f"Woof! I heard you say {command}.")  # Playful dog response


if __name__ == "__main__":
    main()