用于播放固定频率声音的Python库

46 投票
6 回答
61725 浏览
提问于 2025-04-15 12:09

我家里有蚊子问题。这通常和程序员没什么关系;不过,我看到一些设备声称可以通过播放17Khz的音调来驱赶这些讨厌的生物。我想用我的笔记本电脑来实现这个。

一种方法是制作一个包含单一固定频率音调的MP3文件(这可以通过Audacity轻松完成),然后用Python库打开它并重复播放。

第二种方法是使用电脑内置的扬声器播放声音。我想找类似于QBasic中的Sound功能:

SOUND 17000, 100

有没有这样的Python库呢?

6 个回答

5

我把我的代码放在这里,因为这样可以帮助程序员更清楚地理解代码是怎么工作的。代码本身就有解释:

#!/usr/bin/env python3
import pyaudio
import struct
import math

FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100

p = pyaudio.PyAudio()


def data_for_freq(frequency: float, time: float = None):
    """get frames for a fixed frequency for a specified time or
    number of frames, if frame_count is specified, the specified
    time is ignored"""
    frame_count = int(RATE * time)

    remainder_frames = frame_count % RATE
    wavedata = []

    for i in range(frame_count):
        a = RATE / frequency  # number of frames per wave
        b = i / a
        # explanation for b
        # considering one wave, what part of the wave should this be
        # if we graph the sine wave in a
        # displacement vs i graph for the particle
        # where 0 is the beginning of the sine wave and
        # 1 the end of the sine wave
        # which part is "i" is denoted by b
        # for clarity you might use
        # though this is redundant since math.sin is a looping function
        # b = b - int(b)

        c = b * (2 * math.pi)
        # explanation for c
        # now we map b to between 0 and 2*math.PI
        # since 0 - 2*PI, 2*PI - 4*PI, ...
        # are the repeating domains of the sin wave (so the decimal values will
        # also be mapped accordingly,
        # and the integral values will be multiplied
        # by 2*PI and since sin(n*2*PI) is zero where n is an integer)
        d = math.sin(c) * 32767
        e = int(d)
        wavedata.append(e)

    for i in range(remainder_frames):
        wavedata.append(0)

    number_of_bytes = str(len(wavedata))  
    wavedata = struct.pack(number_of_bytes + 'h', *wavedata)

    return wavedata


def play(frequency: float, time: float):
    """
    play a frequency for a fixed time!
    """
    frames = data_for_freq(frequency, time)
    stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, output=True)
    stream.write(frames)
    stream.stop_stream()
    stream.close()


if __name__ == "__main__":
    play(400, 1)
28

这个模块 winsound 是Python自带的,所以你不需要安装任何额外的库,它应该能满足你的需求(而且功能不多)。

 import winsound
 winsound.Beep(17000, 100)

使用起来非常简单方便,不过这个模块只适用于Windows系统。

但是:
要完整回答这个问题,需要说明的是,虽然这个方法可以发出声音,但并不能驱赶蚊子。这已经经过测试了,具体可以查看 这里这里

29

PyAudiere 是一个简单的跨平台解决方案,用来解决以下问题:

>>> import audiere
>>> d = audiere.open_device()
>>> t = d.create_tone(17000) # 17 KHz
>>> t.play() # non-blocking call
>>> import time
>>> time.sleep(5)
>>> t.stop()

pyaudiere.org 网站已经关闭了。你可以通过这个链接找到网站的存档,以及适用于 Python 2 的安装包(适用于 Debian 和 Windows)。比如,你可以在这里下载源代码 pyaudiere-0.2.tar.gz

如果你想在 Linux、Windows 和 OSX 上同时支持 Python 2 和 3,可以使用pyaudio 模块来代替:

#!/usr/bin/env python
"""Play a fixed frequency sound."""
from __future__ import division
import math

from pyaudio import PyAudio # sudo apt-get install python{,3}-pyaudio

try:
    from itertools import izip
except ImportError: # Python 3
    izip = zip
    xrange = range

def sine_tone(frequency, duration, volume=1, sample_rate=22050):
    n_samples = int(sample_rate * duration)
    restframes = n_samples % sample_rate

    p = PyAudio()
    stream = p.open(format=p.get_format_from_width(1), # 8bit
                    channels=1, # mono
                    rate=sample_rate,
                    output=True)
    s = lambda t: volume * math.sin(2 * math.pi * frequency * t / sample_rate)
    samples = (int(s(t) * 0x7f + 0x80) for t in xrange(n_samples))
    for buf in izip(*[samples]*sample_rate): # write several samples at a time
        stream.write(bytes(bytearray(buf)))

    # fill remainder of frameset with silence
    stream.write(b'\x80' * restframes)

    stream.stop_stream()
    stream.close()
    p.terminate()

示例:

sine_tone(
    # see http://www.phy.mtu.edu/~suits/notefreqs.html
    frequency=440.00, # Hz, waves per second A4
    duration=3.21, # seconds to play sound
    volume=.01, # 0..1 how loud it is
    # see http://en.wikipedia.org/wiki/Bit_rate#Audio
    sample_rate=22050 # number of samples per second
)

这是一个修改过的版本(支持 Python 3),来源于这个 AskUbuntu 的回答

撰写回答