Search code examples
pythoncallpyaudio

Call in 3G modem Python, PyAudio


I have two python scripts. The first calls with At Commands, and second receives audio and sends it to the computer microphone. The problem is that when I send the audio the modem resets or is very slow to listen.

First (docall.py)

import serial

se = serial.Serial()
se.port = 5
se.baudrate = 9600 # may be different
se.timeout = 0.5

a=1
se.open()
cont=0
while (a==1):
 if not se.isOpen():
  se.open()
 if cont == 1:
  se.write('AT+CHUP;\r\n')
  se.write('ATD*264;\r\n')
 if cont == 2:
  se.write('AT^DDSETEX?;\r\n')
 if cont == 3:
  se.write('AT^DDSETEX=2;\r\n')

 line = se.read(1024)
 print (line)
 cont=cont+1

se.close()

Second (audio.py)

import serial
import pyaudio
import wave
import time

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 8000
RECORD_SECONDS = 10
WIDTH = 2

pe = pyaudio.PyAudio()

stream= pe.open(format=pe.get_format_from_width(WIDTH),
                channels=CHANNELS,
                rate=RATE,
                output=True,
                frames_per_buffer=CHUNK)

mic= pe.open(format=pyaudio.paInt16,
                channels=1,
                rate=8000,
                input=True,
                frames_per_buffer=128)

se = serial.Serial()
se.port = 3
se.baudrate = 9600 # may be different
se.timeout = 0.5
se.open()
se.writeTimeout = 0

streaming = []
frames = []
while True:
 re= se.read(CHUNK)
 stream.write(re)
 se.write(mic.read(612))

Solution

  • You need to make the frame buffer 160 in order to match the device rate. I'm using the pa device callback in order to write and read from the device, the key number is 320 frame per buffer.

    device = Serial('/dev/tty.HUAWEIMobile-Diag', timeout=None,  writeTimeout=0)
    
    time.sleep(0.1) #this sleep needed for device buffer clean
    device.flush()
    device.flushInput()
    device.flushOutput()
    
    uni_stream = pe.open(format=pyaudio.paInt16,
                         channels=1,
                         rate=8000,
                         input=True,
                         output=True,
                         frames_per_buffer=160, stream_callback=uni_callback)
    
    def uni_callback(in_data, frame_count, time_info, status):
        data = device.read(320)
        device.write(in_data)
    
        return (data, pyaudio.paContinue)