【问题标题】:How can I play a sine/square wave using Pygame?如何使用 Pygame 播放正弦波/方波?
【发布时间】:2020-09-20 15:22:54
【问题描述】:

我正在尝试使用 Pygame 的 sndarray.make_sound 函数播放正弦波。但是,当我使用这个数组来播放它时:

np.sin(2 * np.pi * np.arange(44100) * 440 / 44100).astype(np.float32)

其中440 是频率,44100 是采样率,取而代之的是响亮、刺耳的噪音。这可以使用pyaudio.PyAudio(),但是我需要一些不会阻止执行的东西。方波也会发生这种情况,但是它在那里什么也没有。我将channels=1 用于mixer.pre_initmixer.init 函数。

我该如何解决这个问题?如果有帮助,我正在使用 Mac。提前致谢!

【问题讨论】:

    标签: python python-3.x pygame playback


    【解决方案1】:

    您可以将 numpy 数组直接加载到 pygame.mixer.Sound 对象和 play 它。出现刺耳的声音是因为您可能正在向混音器发送 32 位浮点样本,而它需要 16 位整数样本。如果要使用 32bit 浮点数的数组,必须将混音器的 init 函数的 size 参数设置为 32:

    import pygame
    import numpy as np
    
    pygame.mixer.init(size=32)
    
    buffer = np.sin(2 * np.pi * np.arange(44100) * 440 / 44100).astype(np.float32)
    sound = pygame.mixer.Sound(buffer)
    
    sound.play(0)
    pygame.time.wait(int(sound.get_length() * 1000))
    

    【讨论】:

    • @AlexSpurling 符合预期
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    相关资源
    最近更新 更多