Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

play raw audio file in python in realtime

Tags:

python

voice

voip

I have a udp server in python that continuously receives voice packets from a client in raw format, array of bytes. How can I play the voice on the server side in real time? Any recommended libraries or ways to do it?

Here is my very simple server code if needed (which I doubt)

import socket

UDP_IP = "192.168.1.105"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    #what to do to stream the incoming voice packets?
like image 678
A_Matar Avatar asked May 02 '17 11:05

A_Matar


People also ask

Can you get Python to play a sound?

You can play sound files with the pydub module. It's available in the pypi repository (install with pip). This module can use PyAudio and ffmpeg underneath.

How do I read a WAV file in Python?

open() This function opens a file to read/write audio data. The function needs two parameters - first the file name and second the mode. The mode can be 'wb' for writing audio data or 'rb' for reading.


1 Answers

PyAudio https://people.csail.mit.edu/hubert/pyaudio/

import pyaudio

p = pyaudio.PyAudio()

stream = p.open(format=pyaudio.paFloat32,
                channels=1,
                rate=44100,
                output=True)

data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes

while data != '':
    stream.write(data)
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes

stream.stop_stream()
stream.close()

p.terminate()

There is a way of using a callback method which might be better.

like image 79
justengel Avatar answered Sep 20 '22 01:09

justengel