gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:58:30 35 4
gpt4 key购买 nike

我家里有蚊子问题。这通常与程序员社区无关;然而,我见过一些声称通过播放 17Khz 音调来阻止这些讨厌的生物的设备。我想用我的笔记本电脑来做这个。

一种方法是使用单一的固定频率音调 (This can easily done by audacity) 创建 MP3,opening it with a python library并反复播放。

第二个是使用计算机内置扬声器播放声音。我正在寻找类似于 QBasic Sound 的东西:

SOUND 17000, 100

有没有相应的python库?

最佳答案

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 消失了。 The site Python 2(debian、windows)的二进制安装程序可通过回路机器获得,例如 here's source code pyaudiere-0.2.tar.gz .

在 Linux、Windows、OSX 上同时支持 Python 2 和 3,pyaudio module可以改用:

#!/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
)

它是 this AskUbuntu answer 的修改版(支持 Python 3) .

关于用于播放固定频率声音的 Python 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/974071/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com