Search code examples
pythonpython-3.xvoice-recognition

Voice controlled music system, How to select music?


I am creating a voice controlled music system. The system I have now works but does its job poorly. It splits the words up and looks at a music selection. But if some songs have the same word in the title I spoke (like I say "of" and it finds 5 songs) it selects the last song in the music list. Does someone know a better way of selecting music?

def detectWords(response):
    response = response.lower()
    words = response.split()

    if 'play' in words:
            os.chdir("/home/pi/Desktop/Stemherkenning/Music")
            for file in glob.glob("*mp3"):
                fileSplit = (file.lower()).split()
                if any(word in fileSplit for word in words):
                    mixer.music.load(file)
                    mixer.music.play()
                    print("Playing " + file) 

    if 'stop' in words:
        print("Stopped")
        mixer.music.stop()

'words' are the words the Google speech recognition has picked up.


Solution

  • There are multiple ways of approaching this problem, with varying degrees of sophistication. This method checks for the song which has most unique words in common with the said phrase, it should help get you started:

    import os
    import glob
    import mixer
    import operator
    
    def title_match(title, songlist):
        """Returns the song from `songlist` whose title has 
        the most unique words in common with `title`.
        If two such songs have the same amount of words intersecting, 
        only returns one song."""
    
        title = set(tuple(title))
        matches = {song: len(title & set(song.lower().split())) for song in songlist}
        result = max(matches.items(), key=operator.itemgetter(1))[0]
    
        return result
    
    
    def detectWords(response):
        response = response.lower()
        words = response.split()
    
        if 'play' in words:
            os.chdir("/home/pi/Desktop/Stemherkenning/Music")
            songlist = [file for file in glob.glob("*mp3")]
            title = words[words.index("play")+1:]
            file = title_match(title, songlist) #grabs closest matching file
            print("Playing: " + file)
            mixer.music.load(file)
            mixer.music.play()
    
        if 'stop' in words:
            print("Stopped")
            mixer.music.stop()