55

问候,

我正在尝试用 Python 编写一个程序,该程序每次在麦克风中被点击时都会打印一个字符串。当我说“敲击”时,我指的是突然发出的响亮的噪音或类似的声音。

我在 SO 中搜索并找到了这篇文章:识别音频的音调

我认为 PyAudio 库会满足我的需求,但我不太确定如何让我的程序等待音频信号(实时麦克风监控),以及当我得到一个如何处理它时(我是否需要使用傅立叶变换之类的上面的帖子中有指示)?

提前感谢您可以给我的任何帮助。

4

3 回答 3

42

如果您使用的是 LINUX,则可以使用pyALSAAUDIO。对于 Windows,我们有PyAudio,还有一个名为SoundAnalyse的库。

我在这里找到了一个 Linux 示例:

#!/usr/bin/python
## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a loop,
## Then prints the volume.
##
## To test it out, run it and shout at your microphone:

import alsaaudio, time, audioop

# Open the device in nonblocking capture mode. The last argument could
# just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)

# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)

# The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api.
# For our purposes, it is suficcient to know that reads from the device
# will return this many frames. Each frame being 2 bytes long.
# This means that the reads below will return either 320 bytes of data
# or 0 bytes of data. The latter is possible because we are in nonblocking
# mode.
inp.setperiodsize(160)

while True:
    # Read data from device
    l,data = inp.read()
    if l:
        # Return the maximum of the absolute value of all samples in a fragment.
        print audioop.max(data, 2)
    time.sleep(.001)
于 2009-12-20T21:10:42.187 回答
7

...当我得到一个如何处理它时(我是否需要像上面的帖子中所指示的那样使用傅立叶变换)?

如果您想要“抽头”,那么我认为您对幅度比对频率更感兴趣。所以傅立叶变换可能对您的特定目标没有用处。您可能希望对输入的短期(例如 10 毫秒)幅度进行运行测量,并检测它何时突然增加某个增量。您需要调整以下参数:

  • 什么是“短期”幅度测量
  • 你要找的增量是多少
  • 增量变化必须以多快的速度发生

虽然我说您对频率不感兴趣,但您可能需要先进行一些过滤,以滤除特别是低频和高频分量。这可能会帮助您避免一些“误报”。您可以使用 FIR 或 IIR 数字滤波器来做到这一点;傅立叶不是必需的。

于 2009-12-20T23:42:20.750 回答
5

我知道这是一个老问题,但如果有人再次看这里......请参阅https://python-sounddevice.readthedocs.io/en/0.4.1/index.html

它有一个很好的例子“输入到输出传递”在这里https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through

...以及许多其他示例...

于 2020-11-13T16:43:05.657 回答