Архив метки: math

Python Генерация звуков через PyAudio

Следующий код генерирует и проигрывает звук:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Генерация звуков через pyaudio.

За основу взят https://medium.com/py-bits/sound-generation-python-904e54f5398d

sudo apt-get install python3-pyaudio
"""

import pyaudio
import math
PyAudio = pyaudio.PyAudio
BITRATE = 5000
FREQUENCY = 10000
LENGTH = 5
if FREQUENCY > BITRATE:
    BITRATE = FREQUENCY + 100
NUMBER_OF_FRAMES = int(BITRATE * LENGTH)
WAVEDATA = ''
for x in range(NUMBER_OF_FRAMES):
    WAVEDATA = WAVEDATA + chr(
        int(
            math.sin(
                x
                / (
                    (
                        BITRATE / FREQUENCY
                    ) / math.pi
                )
            ) * 127 + 128
        )
    )
REST_FRAMES = NUMBER_OF_FRAMES % BITRATE
for x in range(REST_FRAMES):
    WAVEDATA = WAVEDATA + chr(128)
# print(WAVEDATA)
# óYªQ±J¹CÀ<Æ5Í/Ó)Ù$Þãèìð
# öùûýþþþþýüúø	õ
# óYªQ±J¹CÀ<Æ5Í/Ó)Ù$ÞãèìðÛ&Ö,Ð2Ê9Ã?¼FµN®U¦\lt|xph
# öùûýþþþþýüúø	õ
# ...
p = PyAudio()
stream = p.open(
    format=p.get_format_from_width(1),
    channels=2,
    rate=BITRATE,
    output=True
)
stream.write(WAVEDATA)
stream.stop_stream()
stream.close()
p.terminate()