gangadhars
gangadhars

Reputation: 2728

Record and play audio - python

I'm going to implement a voice chat using python. So I saw few examples, how to play sound and how to record. In many examples they used pyAudio library.
I'm able to record voice and able to save it in .wav file. And I'm able play a .wav file. But I'm looking for record voice for 5 seconds and then play it. I don't want to save it into file and then playing, it's not good for voice chat.

Here is my audio record code:

p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT, channels=1, rate=RATE,
        input=True, output=True,
        frames_per_buffer=CHUNK_SIZE)
num_silent = 0
snd_started = False

r = array('h')

while 1:
    # little endian, signed short
    snd_data = array('h', stream.read(CHUNK_SIZE))
    if byteorder == 'big':
        snd_data.byteswap()
    r.extend(snd_data)

    silent = is_silent(snd_data)

    if silent and snd_started:
        num_silent += 1
    elif not silent and not snd_started:
        snd_started = True

    if snd_started and num_silent > 30:
        break

Now I want to play it without saving. I don't know how to do it.

Upvotes: 4

Views: 6643

Answers (2)

Mohamed Nagy
Mohamed Nagy

Reputation: 21

I do not like this library try 'sounddevice' and 'soundfile'its are very easy to use and to implement. for record and play voice use this:

import sounddevice as sd
import soundfile as sf 


sr = 44100
duration = 5
myrecording = sd.rec(int(duration * sr), samplerate=sr, channels=2)
sd.wait()  
sd.play(myrecording, sr)
sf.write("New Record.wav", myrecording, sr)

Upvotes: 2

randomusername
randomusername

Reputation: 8105

Having looked through the PyAudio Documentation, you've got it all as it should be but what you're forgetting is that stream is a duplex descriptor. This means that you can read from it to record sound (as you have done with stream.read) and you write to it to play sound (with stream.write).

Thus the last few lines of your example code should be:

# Play back collected sound.
stream.write(r)

# Cleanup the stream and stop PyAudio
stream.stop_stream()
stream.close()
p.terminate()

Upvotes: 1

Related Questions