在Python中调用3G调制解调器,使用PyAudio
我有两个Python脚本。第一个脚本是用AT命令进行调用,第二个脚本是接收音频并把它发送到电脑的麦克风。现在的问题是,当我发送音频时,调制解调器要么重启,要么反应很慢,听不清楚。
第一个脚本(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()
第二个脚本(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))
1 个回答
0
你需要把帧缓冲区设置为160,这样才能和设备的速率匹配。我正在使用pa设备的回调函数来进行设备的读写,关键的数字是每个缓冲区320帧。
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)