使用pygame频道的立体声效果在while循环中失败(python)

2024-09-29 23:19:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在建立一个应用程序,目前发挥音阶。代码如下:

from numpy import linspace, sin, pi, int16
import pygame.mixer, pygame.sndarray, time
# tone synthesis
def note(freq, len, amp = 1, rate = 44100):
    t = linspace(0, len, len * rate)
    data = sin(2 * pi * freq * t) * amp
    return data.astype(int16) # two byte integers

pygame.mixer.init(22050, -16, 2, 1000)
pygame.mixer.init()
cleft=pygame.mixer.Channel(0)
cleft.set_volume(1, 0)
cright=pygame.mixer.Channel(1)
cright.set_volume(0, 1)


x=0
pitches=[523, 554, 587, 622, 659, 698, 739, 784, 830, 880, 932, 987, 1046]
majorscale=[0, 2, 4, 5, 7, 9, 11, 12]
minorscale=[0, 2, 3, 5, 7, 9, 10, 12]
while x<8:
    toneL = note(pitches[minorscale[x]], .2, amp=8000)
    toneR = note(pitches[minorscale[x]], .2, amp=0)
    snd_outL = pygame.mixer.Sound(toneL)
    snd_outR = pygame.mixer.Sound(toneR)
    cleft.play(snd_outL)
    cright.play(snd_outR)
    x += 1
    time.sleep(.2)

在while循环的前两行中,我设置了“amp”属性,以便音频只能从左声道输出。这在循环的第一次迭代中起作用,但它在音频上循环的剩余时间是单声道的,我在两只耳朵里听到完全相同的声音。我失去了立体声效果。有人知道为什么吗?只要你下载了numpy和pygame,你就可以复制这个代码并自己尝试。你知道吗


Tags: 代码importnumpylensinpygamenoteamp

热门问题