首页 > 解决方案 > Python从rtsp流中获取音频数据

问题描述

我正在尝试从带有 Python 3.7 的 mlaw 格式的 rstp 流中获取音频数据。我希望能够像使用 pyaudio 一样将它放在一个 numpy 数组中。然后当有声音时,记录它。它不是总是有音频噪音的东西。

这就是我使用物理输入为 Pyaudio 编码的方式。基本上我也想做同样的事情,而是使用来自 URL 的 RTSP 流。

p = pyaudio.PyAudio()
stream = self.p.open(format=FORMAT,
                     channels=CHANNELS,
                     rate=RATE,
                     input=True,
                     output=True,
                     frames_per_buffer=chunk)

def listen(self):
  print('Listening beginning')
  while True:
      input = self.stream.read(chunk)
      rms_val = self.rms(input)
      if rms_val > Threshold:
          record()

def record():
    print('Noise detected, recording beginning')
    rec = []
    rec_start = time.time()
    current = time.time()
    end = time.time() + TIMEOUT_LENGTH

    while current <= end:

        data = self.stream.read(chunk)
        if rms(data) >= Threshold: end = time.time() + 2

        current = time.time()
        rec.append(data)

def rms(frame):
    count = len(frame) / swidth
    format = "%dh" % (count)
    shorts = struct.unpack(format, frame)
    sum_squares = 0.0
    for sample in shorts:
        n = sample * SHORT_NORMALIZE
        sum_squares += n * n
    rms = math.pow(sum_squares / count, 0.5)
    return rms * 1000

这是我为 ffmpeg 尝试过的,但它只是冻结而没有错误并且不打印任何数据。它甚至实际上使带有 rtsp 流的 IoT 设备崩溃。有没有办法我可以用 urllib 或 requests 甚至是用子进程打开的 ffmpeg 命令来做到这一点?

import ffmpeg

packet_size = 4096

process = ffmpeg.input('rtsp://192.168.1.122:554/au:scanner.au').output('-', format='mulaw').run_async(pipe_stdout=True)
packet = process.stdout.read(packet_size)

while process.poll() is None:
    packet = process.stdout.read(packet_size)
    print(packet)

我的最终结果是做两件事。一个在有音频时录制 wav,第二个,从录制的 wav 转换并将该音频作为 opus 和 mp3 上传到 SFTP。

标签: python-3.xffmpeg

解决方案


推荐阅读