gpt4 book ai didi

python - pygame音频代码不起作用

转载 作者:行者123 更新时间:2023-12-03 00:47:26 31 4
gpt4 key购买 nike

该代码似乎可以正常运行,但是除了打开pygame窗口外,实际上并没有做任何应做的事情。我正在寻找按“z”键时要播放的声音。

有人可以看到此代码有问题吗?

import pygame
from pygame.locals import *
import math
import numpy

size = (1200, 720)
screen = pygame.display.set_mode(size, pygame.HWSURFACE | pygame.DOUBLEBUF)
pygame.display.set_caption('Nibbles!')

SAMPLE_RATE = 22050 ## This many array entries == 1 second of sound.

def SineWave(freq=1000,volume=16000,length=1):
num_steps = length*SAMPLE_RATE
s = []
for n in range(num_steps):
value = int(math.sin(n * freq * (6.28318/SAMPLE_RATE) * length)*volume)
s.append( [value,value] )
x_arr = array(s)
return x_arr

def SquareWave(freq=1000,volume=100000,length=1):
length_of_plateau = SAMPLE_RATE / (2*freq)
s = []
counter = 0
state = 1
for n in range(length*SAMPLE_RATE):
if state == 1:
value = volume
else:
value = -volume
s.append( [value,value] )

counter += 1
if counter == length_of_plateau:
counter = 0
if state == 1:
state = -1
else:
state = 1

x_arr = array(s)
return x_arr

def MakeSound(arr):
return pygame.sndarray.make_sound(arr)

def PlaySquareWave(freq=1000):
MakeSound(SquareWave(freq)).play()

def PlaySineWave(freq=1000):
MakeSound(SineWave(freq)).play()

def StopSineWave(freq=1000):
MakeSound(SineWave(freq)).fadeout(350)

def StopSquareWave(freq=1000):
MakeSound(SquareWave(freq)).fadeout(350)

_running = True
while _running:

SineWaveType = 'Sine'
SquareWaveType = 'Square'
d = {SineWaveType:SquareWaveType, SquareWaveType:SineWaveType}
Type = SineWaveType

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

if Type == 'Sine':

if event.type == KEYDOWN:

#lower notes DOWN
if event.key == K_ESCAPE:
_running = False

if event.key == K_ENTER:
Type = d[Type] #Toggle

elif event.key == K_z:
PlaySineWave(130.81)

if event.type == KEYUP:

#lower notes UP

if event.key == K_z:
StopSineWave(130.81).fadeout(350) #fade sound by .35 seconds

elif Type == 'Square':

if event.type == KEYDOWN:

#lower notes DOWN
if event.key == K_z:
PlaySquareWave(130.81)

if event.type == KEYUP:

#lower notes UP

if event.key == K_z:
StopSquareWave(130.81).fadeout(350) #fade sound by .35 seconds

pygame.quit()

最佳答案

编辑(2019.03.06):现在代码可在Python 3上使用-感谢评论中的Tomasz Gandor建议。

一些修改:

  • 您必须淡出现有声音,而不能创建新的淡出声音(因为pygame将同时播放两者)-我使用curren_played保留现有声音。
  • ESCAPEENTER不必检查声音类型。
  • 您忘记了初始化屏幕,混音器等的pygame.init()
  • 因为我遇到方波问题,所以在示例中使用正弦波。
  • 我将sonund添加到c键-这样您可以同时播放两种声音
  • 我将大写名称用于诸如SINE_WAVE_TYPE的常量值。

  • 您可以在 mainloop之前创建wave,并将其保留在 current_played中,并在按 current_played时在 RETURN中生成新的wave

    import pygame
    from pygame.locals import *
    import math
    import numpy

    #----------------------------------------------------------------------
    # functions
    #----------------------------------------------------------------------

    def SineWave(freq=1000, volume=16000, length=1):

    num_steps = length * SAMPLE_RATE
    s = []

    for n in range(num_steps):
    value = int(math.sin(n * freq * (6.28318/SAMPLE_RATE) * length) * volume)
    s.append( [value, value] )

    return numpy.array(s, dtype=numpy.int32) # added dtype=numpy.int32 for Python3

    def SquareWave(freq=1000, volume=100000, length=1):

    num_steps = length * SAMPLE_RATE
    s = []

    length_of_plateau = SAMPLE_RATE / (2*freq)

    counter = 0
    state = 1

    for n in range(num_steps):

    value = state * volume
    s.append( [value, value] )

    counter += 1

    if counter == length_of_plateau:
    counter = 0
    state *= -1

    return numpy.array(s, dtype=numpy.int32) # added dtype=numpy.int32 for Python3

    def MakeSound(arr):
    return pygame.sndarray.make_sound(arr)

    def MakeSquareWave(freq=1000):
    return MakeSound(SquareWave(freq))

    def MakeSineWave(freq=1000):
    return MakeSound(SineWave(freq))

    #----------------------------------------------------------------------
    # main program
    #----------------------------------------------------------------------

    pygame.init()

    size = (1200, 720)
    screen = pygame.display.set_mode(size, pygame.HWSURFACE | pygame.DOUBLEBUF)
    pygame.display.set_caption('Nibbles!')

    SAMPLE_RATE = 22050 ## This many array entries == 1 second of sound.

    SINE_WAVE_TYPE = 'Sine'
    SQUARE_WAVE_TYPE = 'Square'

    sound_types = {SINE_WAVE_TYPE:SQUARE_WAVE_TYPE, SQUARE_WAVE_TYPE:SINE_WAVE_TYPE}

    current_type = SINE_WAVE_TYPE

    current_played = { 'z': None, 'c': None }

    _running = True
    while _running:

    for event in pygame.event.get():

    if event.type == pygame.QUIT:
    _running = False

    # some keys don't depend on `current_type`

    elif event.type == KEYDOWN:

    if event.key == K_ESCAPE:
    _running = False

    if event.key == K_RETURN:
    current_type = sound_types[current_type] #Toggle
    print('new type:', current_type) # added () for Python3

    # some keys depend on `current_type`

    if current_type == SINE_WAVE_TYPE:

    if event.type == KEYDOWN:

    #lower notes DOWN

    if event.key == K_z:
    print(current_type, 130.81) # added () for Python3
    current_played['z'] = MakeSineWave(130.81)
    current_played['z'].play()

    elif event.key == K_c:
    print(current_type, 180.81) # added () for Python3
    current_played['c'] = MakeSineWave(180.81)
    current_played['c'].play()

    elif event.type == KEYUP:

    #lower notes UP

    if event.key == K_z:
    current_played['z'].fadeout(350)
    elif event.key == K_c:
    current_played['c'].fadeout(350)

    elif current_type == SQUARE_WAVE_TYPE:

    if event.type == KEYDOWN:

    #lower notes DOWN

    if event.key == K_z:
    print(current_type, 80.81) # added () for Python3
    current_played['z'] = MakeSineWave(80.81)
    #current_played['z'] = MakeSquareWave(130.81)
    current_played['z'].play()

    elif event.key == K_c:
    print(current_type, 180.81) # added () for Python3
    current_played['c'] = MakeSineWave(180.81)
    #current_played['c'] = MakeSquareWave(130.81)
    current_played['c'].play()

    elif event.type == KEYUP:

    #lower notes UP

    if event.key == K_z:
    current_played['z'].fadeout(350)
    elif event.key == K_c:
    current_played['c'].fadeout(350)

    pygame.quit()

    关于python - pygame音频代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24888382/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com