Pygame 按频率播放噪音、按住并同时播放音符

问题描述 投票:0回答:1
import pygame
import numpy as np
import math

pygame.init()

# Set the sample rate and bit size for the audio
pygame.mixer.init(frequency=44100, size=-16, channels=10, buffer=2**12)

# Create a small window in the background (1x1 size)
pygame.display.set_mode((1, 1), pygame.NOFRAME)

# Define the piano sounds
frequencies = [
    {"Note": "C2", "Frequency": 65.41},
    {"Note": "C", "Frequency": 130.81},
    {"Note": "D", "Frequency": 146.83},
    {"Note": "E", "Frequency": 164.81},
    # Add more notes as needed
]

# Create a dictionary to map key codes to notes and channels
key_mapping = {
    pygame.K_a: {"Note": "C2", "Channel": None},
    pygame.K_s: {"Note": "C", "Channel": None},
    pygame.K_d: {"Note": "D", "Channel": None},
    pygame.K_f: {"Note": "E", "Channel": None},
    # Add more key mappings as needed
}

# Create sound objects for each note
sounds = {}
for note_info in frequencies:
    note = note_info["Note"]
    frequency = note_info["Frequency"]

    wave_array = np.array([int(32767.0 * math.sin(2.0 * math.pi * frequency * t / 44100.0)) for t in range(44100)], dtype=np.int16)
    sound = pygame.mixer.Sound(wave_array)
    sounds[note] = sound

# Main loop
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            key = event.key
            if key in key_mapping:
                note_info = key_mapping[key]
                note = note_info["Note"]
                if note_info["Channel"] is None:
                    prit(f"Played {note}")
                    channel = pygame.mixer.find_channel()
                    if channel:
                        channel.play(sounds[note], loops=-1)
                        note_info["Channel"] = channel
        elif event.type == pygame.KEYUP:
            key = event.key
            if key in key_mapping:
                note_info = key_mapping[key]
                note = note_info["Note"]
                if note_info["Channel"]:
                    print(f"Stopped {note}")
                    note_info["Channel"].stop()
                    note_info["Channel"] = None

# Clean up
pygame.quit()

我的代码使你的按键 A、S、D、F 按频率播放不同的音符,但我无法让它们顺利按住,有谁知道我该如何解决这个问题?另外,当我同时按下两个键时,它会发出奇怪的声音,有没有办法解决这两个问题? PS:您需要打开弹出的 pygame 窗口才能使用按键绑定

我尝试在不同的通道中播放相同的音符,延迟以平滑循环,但仍然不起作用。我还尝试在不同的通道中演奏不同的音符,这样在同时演奏 2 个音符时就不会发出奇怪的声音

python audio pygame
1个回答
0
投票

但我无法让它们顺利握持

您抱怨音频中有 1 Hz 的咔嗒声。

您生成了一个非常平滑的 1 秒中间 C 正弦波样本 或者其他什么,然后你突然切换到另一个 类似正弦波的样本。 波浪不匹配。

您可以通过使样本匹配来解决这个问题。 或者更简单地使用交叉淡入淡出,其中短暂的间隔 我们混合在一起(相加)

f
× 旧样本 加上
(1 - f)
× 新样本。

当我同时按下2个键时,会发出奇怪的声音

我们将其描述为一个频率 “殴打反对” 另一个频率,它是基本的。 例如,参见描述 调频 调频。 巴赫的背景故事 平均律键盘 就是为了应对这种影响 以一种美观的方式。 您可以自由更改 频率 与每个按键相关联, 努力打造一款经过精心打磨的电脑键盘。

© www.soinside.com 2019 - 2024. All rights reserved.