Python Forum

Full Version: I'm new to Python - can someone help with this code as it is not working?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Voice-Controlled Hindi Song Player
------------------------------------------

Here's how the application should work:

Create a directory called "hindi_songs" and place your Hindi MP3 songs there
Run the script
The app will greet you in Hindi and wait for your voice commands
You can give commands like:

"गाना चलाओ [song name]" to play a song
"बंद करो" or "रोको" to stop the current song
"बाहर" or "बाय" to exit the application

Key features:

Voice recognition specifically configured for Hindi
Text-to-speech responses in Hindi
Automatic song search in the specified directory
Ability to stop and play songs with voice commands
Error handling for various scenarios
-------------------------------------------------------------

import speech_recognition as sr
import pygame
import os
from gtts import gTTS
import time
import threading

class VoiceHindiPlayer:
    def __init__(self, songs_directory="hindi_songs"):
        """Initialize the voice-controlled Hindi song player."""
        self.recognizer = sr.Recognizer()
        self.songs_directory = songs_directory
        self.currently_playing = None
        self.is_playing = False
        
        # Initialize pygame mixer for audio playback
        pygame.mixer.init()
        
        # Create songs directory if it doesn't exist
        if not os.path.exists(songs_directory):
            os.makedirs(songs_directory)
            
    def speak(self, text, lang='hi'):
        """Convert text to speech and play it."""
        tts = gTTS(text=text, lang=lang)
        tts.save("response.mp3")
        pygame.mixer.music.load("response.mp3")
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            time.sleep(0.1)
        os.remove("response.mp3")

    def listen_command(self):
        """Listen for voice commands and convert to text."""
        with sr.Microphone() as source:
            print("Listening for command...")
            self.recognizer.adjust_for_ambient_noise(source)
            try:
                audio = self.recognizer.listen(source, timeout=5)
                command = self.recognizer.recognize_google(audio, language='hi-IN')
                print(f"Command recognized: {command}")
                return command.lower()
            except sr.UnknownValueError:
                print("Could not understand audio")
                return None
            except sr.RequestError:
                print("Could not request results")
                return None
            except Exception as e:
                print(f"Error: {str(e)}")
                return None

    def play_song(self, song_name):
        """Play the specified song."""
        try:
            # Find the song file
            song_path = None
            for file in os.listdir(self.songs_directory):
                if song_name.lower() in file.lower():
                    song_path = os.path.join(self.songs_directory, file)
                    break

            if song_path and os.path.exists(song_path):
                # Stop currently playing song if any
                if self.is_playing:
                    pygame.mixer.music.stop()
                
                # Play the new song
                pygame.mixer.music.load(song_path)
                pygame.mixer.music.play()
                self.is_playing = True
                self.currently_playing = song_name
                self.speak(f"अब बज रहा है {song_name}", 'hi')
            else:
                self.speak("माफ़ कीजिये, गाना नहीं मिला", 'hi')
        except Exception as e:
            print(f"Error playing song: {str(e)}")
            self.speak("गाना चलाने में समस्या आई है", 'hi')

    def stop_song(self):
        """Stop the currently playing song."""
        if self.is_playing:
            pygame.mixer.music.stop()
            self.is_playing = False
            self.currently_playing = None
            self.speak("गाना रुक गया है", 'hi')

    def run(self):
        """Main loop to run the voice-controlled player."""
        self.speak("नमस्ते! मैं आपका संगीत सहायक हूं। आप कौन सा गाना सुनना चाहेंगे?", 'hi')
        
        while True:
            command = self.listen_command()
            
            if command:
                if "बंद करो" in command or "रोको" in command:
                    self.stop_song()
                elif "चलाओ" in command or "बजाओ" in command:
                    # Extract song name from command
                    song_words = command.split()
                    song_name = " ".join(word for word in song_words 
                                       if word not in ["चलाओ", "बजाओ"])
                    self.play_song(song_name)
                elif "बाहर" in command or "बाय" in command:
                    self.speak("अलविदा!", 'hi')
                    break

if __name__ == "__main__":
    player = VoiceHindiPlayer()
    player.run()
Thanks Buran, your point is very well noted!