Search code examples
pythonaudiodirectsound

Storing sounds on Python


I have been trying to get my python code to store sounds based on inputs. i am struggling to develop the code and all resources I've found online haven't been helpful. Can anyone give me some suggesttions?

I am trying to create a program that stores a users name and asks them to say it and the sound is stored for each particular name. It can also be played back as well.


Solution

  • So from what I understand, you want to save audio file for each names and then ask user for his/her name. If name matches, then you want to play file containing his/her name. If above understanding is correct, you can achieve that in several ways.

    Easiest way will be to store names you desire in some audio format (eg. wav). Here I've got audio pronunciation of few US cities from web. Next you store these files in a folder.

    For demo purpose I've code and audio files of names in same folder.

    Next using python we create a dictionary with key as names and its corresponding audio files as values.

    You can make it fancy by reading through a folder and generating dictionary on the fly with file name as key (an excersize for you).

    Since you've used Directsound tag, I am assuming you are using windows. You can use winsound library(which I believe is standard library)

    Then you can ask user for his/her name. If name matches with key value in dictionary , you can play the name, else play error file.

    Working Code

    import winsound
    
    names = {'NewYork' : 'NewYork.wav',
             'LosAngeles' : 'LosAngeles.wav',
             'Denver' : 'Denver.wav',
             'Dallas' : 'Dallas.wav'         
             }
    
    def error():
        print("{} not in database".format(name))
        winsound.Beep(2500, 1000) #freq, duration in ms
    
    name = raw_input("enter name:")
    if name in names:
        winsound.PlaySound(names.get(name), winsound.SND_FILENAME)
    else:
        error()