简单的Pygame音频频率

Pau*_*aul 7 python audio pygame

如何在Pygame中使用音频创建一个能够流畅播放的440 Hz声音?我认为这应该很容易,但我不想使用任何愚蠢的文件来完成任务.这样做的最终目的是在我按照另一个问题提出的要求按下按键时播放音符.任何帮助将不胜感激,因为我浪费了大量的时间试图找到答案.

odd*_*eta 8

在获得完全过多的"ValueError:数组深度必须与混频器通道数匹配"以及其他类似错误后,我发现了这个工作示例http://www.mail-archive.com/pygame-users@seul.org/msg16140. HTML.它可以正确生成一个多维16位整数数组,可与立体声混音器配合使用.下面的最小工作示例,大部分从上一个链接中提取所需的pygame位.使用pygame.ver'1.9.1release'在Python 2.7.2中测试.

此示例将在立体声设置中播放一个扬声器的440 Hz音调和另一个扬声器的550 Hz音调.经过一段时间的播放后,我发现如果将"duration"变量设置为除整数之外的任何值,声音循环中会弹出声音点击.

import pygame
from pygame.locals import *

import math
import numpy

size = (1366, 720)

bits = 16
#the number of channels specified here is NOT 
#the channels talked about here http://www.pygame.org/docs/ref/mixer.html#pygame.mixer.get_num_channels

pygame.mixer.pre_init(44100, -bits, 2)
pygame.init()
_display_surf = pygame.display.set_mode(size, pygame.HWSURFACE | pygame.DOUBLEBUF)


duration = 1.0          # in seconds
#freqency for the left speaker
frequency_l = 440
#frequency for the right speaker
frequency_r = 550

#this sounds totally different coming out of a laptop versus coming out of headphones

sample_rate = 44100

n_samples = int(round(duration*sample_rate))

#setup our numpy array to handle 16 bit ints, which is what we set our mixer to expect with "bits" up above
buf = numpy.zeros((n_samples, 2), dtype = numpy.int16)
max_sample = 2**(bits - 1) - 1

for s in range(n_samples):
    t = float(s)/sample_rate    # time in seconds

    #grab the x-coordinate of the sine wave at a given time, while constraining the sample to what our mixer is set to with "bits"
    buf[s][0] = int(round(max_sample*math.sin(2*math.pi*frequency_l*t)))        # left
    buf[s][1] = int(round(max_sample*0.5*math.sin(2*math.pi*frequency_r*t)))    # right

sound = pygame.sndarray.make_sound(buf)
#play once, then loop forever
sound.play(loops = -1)


#This will keep the sound playing forever, the quit event handling allows the pygame window to close without crashing
_running = True
while _running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            _running = False
            break

pygame.quit()
Run Code Online (Sandbox Code Playgroud)


Tha*_*tos 5

什么样的440赫兹声音?“440 Hz”有多种类型的波:正弦波、锯齿波、方波等。你可以让长笛演奏 A,这也很重要。

假设您想要一个正弦波,看起来您可以使用pygame.sndarray.samples. (我还没有测试过)您可以使用以下方法创建示例:

samples = [math.sin(2.0 * math.pi * frequency * t / sample_rate) for t in xrange(0, duration_in_samples)]
Run Code Online (Sandbox Code Playgroud)

这希望是基本的正弦波东西。frequency是所需的频率,以赫兹为单位。sample_rate是生成的音频中的采样数/秒:44100 Hz 是典型值。duration_in_samples是音频的长度。(5 * 44100 == 5 秒,如果您的音频采样率为 44100 Hz。)

它看起来像你可能要转换samplesnumpy.array传递给前pygame.sndarray.samples。文档表明音频应与 返回的格式相匹配pygame.mixer.get_init,因此请samples适当调整,但这是基本思想。(mixer.get_init会告诉你sample_rate上面变量,以及是否需要考虑立体声,以及是否需要调整波的幅度或移动它。)

制作samples整数个波浪长,它应该循环。