How can I record a sound and play it back after a user-defined delay in Python?
Question: I'm looking for a Python's code that would record a sound and play it back
after a certain delay (for example 10 seconds). In other words, I would like
to constantly hear (on my headphones) what's going on outside, but with a
certain delay.

I found a Python script on GitHub
(<https://gist.github.com/larsyencken/5641402>) that is supposed to do what
I'm looking for. However, when I run the script, the playing starts after 5
seconds (default delay), but it records everything around and plays it in real
time (without any delay).


Answer: Here is an example using `sounddevice` , although you can do it using other
`audio/sound` modules as well.

Below example records audio from microphone for `#seconds` as per variable
`duration` which you can modify as per your requirements. Same contents are
played back using standard audio output (speakers). More on this
[here](http://python-sounddevice.readthedocs.io/en/0.3.4/)

**Working Code**

    
    
    import sounddevice as sd
    import numpy as np
    import scipy.io.wavfile as wav
    
    fs=44100
    duration = 10  # seconds
    myrecording = sd.rec(duration * fs, samplerate=fs, channels=2, dtype='float64')
    print "Recording Audio for %s seconds" %(duration)
    sd.wait()
    print "Audio recording complete , Playing recorded Audio"
    sd.play(myrecording, fs)
    sd.wait()
    print "Play Audio Complete"
    

**Output**

    
    
    Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> ================================ RESTART ================================
    >>> 
    Recording Audio for 10 seconds
    Audio recording complete , Playing recorded Audio
    Play Audio Complete
    >>> 
    

