Библиотека Python для воспроизведения звука с фиксированной частотой - PullRequest
29 голосов
/ 10 июня 2009

У меня проблема с комарами в моем доме. Это обычно не касается сообщества программистов; Тем не менее, я видел несколько устройств, которые утверждают, что удерживают этих мерзких существ, играя тон 17 кГц. Я хотел бы сделать это, используя свой ноутбук.

Одним из методов будет создание MP3 с одним тоном фиксированной частоты ( Это легко сделать с помощью Audacity ), , открытие его с библиотекой Python и повторное его воспроизведение.

Второй будет воспроизводить звук, используя встроенный динамик компьютера. Я ищу что-то похожее на QBasic Sound :

SOUND 17000, 100

Есть ли для этого библиотека Python?

Ответы [ 4 ]

20 голосов
/ 10 июня 2009

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.

Для поддержки Python 2 и 3 в Linux вместо Windows можно использовать 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 .

14 голосов
/ 10 июня 2009

Модуль winsound включен в Python, поэтому внешние библиотеки для установки отсутствуют, и он должен делать то, что вы хотите (и не намного).

 import winsound
 winsound.Beep(17000, 100)

Это очень просто и легко, хотя доступно только для Windows.

Но:
В полном ответе на этот вопрос следует отметить, что хотя этот метод будет издавать звук, он не будет удерживать комаров . Это уже было проверено: см. здесь и здесь

2 голосов
/ 09 ноября 2018

Я помещаю свой код сюда, чтобы он помог программисту понять, как работает код

объяснение в самом коде

#!/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)
0 голосов
/ 10 июня 2009

Вы можете использовать привязку Python SDL ( Simple Direct Media Library ).

...