python - pyaudio在python2和python3中播放不同的音调

标签 python python-3.x python-2.7 audio pyaudio

我刚刚开始使用pyaudio,我写了一个简单的函数来演奏音符。但是,根据我使用的Python版本,注释听起来有所不同:

from __future__ import division
import math
import pyaudio


BITS_PER_BYTE = 8  # for clarity
SAMPLE_BIT_DEPTH = 8  # i.e. each sample is 1 byte
SAMPLES_PER_SECOND = 16000
NOTE_TIME_SECONDS = 1
MIDDLE_C_HZ = 523.3

CYCLES_PER_SECOND = SAMPLES_PER_SECOND / MIDDLE_C_HZ
NUM_SAMPLES = SAMPLES_PER_SECOND * NOTE_TIME_SECONDS


def play_note():
    audio = pyaudio.PyAudio()

    stream = audio.open(
        format=audio.get_format_from_width(SAMPLE_BIT_DEPTH / BITS_PER_BYTE),
        channels=1,
        rate=SAMPLES_PER_SECOND,
        output=True,
    )

    byte_string = str()

    for i in range(NUM_SAMPLES):
        # calculate the amplitude for this frame as a float between -1 and 1
        frame_amplitude = math.sin(i / (CYCLES_PER_SECOND / math.pi))
        # scale the amplitude to an integer between 0 and 255 (inclusive)
        scaled_amplitude = int(frame_amplitude * 127 + 128)
        # convert amplitude to byte string (ascii value)
        byte_string += chr(scaled_amplitude)

    stream.write(byte_string)
    stream.close()
    audio.terminate()


if __name__ == '__main__':
    play_note()

在Python 2.7.13中,我听到正确,清晰的音调。在3.6.2中,听起来像方波。

为什么会这样,我将如何解决(或至少开始调试)呢?

我正在使用portaudio v10.11.6在OSX v19.6.0上。

最佳答案

这是因为当您应该使用str时,您正在使用byte

这对我有用:

byte_array = bytearray()  # bytearray instead of str

for i in range(NUM_SAMPLES):
    frame_amplitude = math.sin(i / (CYCLES_PER_SECOND / math.pi))
    scaled_amplitude = int(frame_amplitude * 127 + 128)
    # Note the append here, not +=
    byte_array.append(scaled_amplitude)

stream.write(bytes(byte_array))

关于python - pyaudio在python2和python3中播放不同的音调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47465730/

相关文章:

python - python 3 与 python 2 中的 ConfigParser

python - Season_decompose 引发错误 : TypeError: PeriodIndex given. 检查 `freq` 属性而不是使用 infer_freq

python - 生成 CSV 和空行

python - python 2.7中列表索引超出范围

python - 使用 Python 从电子邮件正文中提取 URL?

python - Pandas 从列表列中获取唯一值

python - 从滚动时添加新表格的页面中抓取 HTML 数据

python 导入本地库而不是内置库

python - 缺少 1 个必需的位置参数 : 'key'

python - 在 Ubuntu 18 中安装 Auto Sklearn