游戏中的音频变化速度

2024-10-05 15:21:40 发布

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

所以我用pygame做了一个游戏,我的问题是某种音效会以不同的速度播放。据我所知,只有两种速度,它会发挥正常,有时会发挥正常,另一次可能会显着更快。在

这里是我的代码的一些部分,我会包括更多,但我无法想象任何其他地方可能会出现问题。知道是什么引起的吗?在

pygame.mixer.pre_init(44000, -16, 2, 512)
pygame.mixer.init()
pygame.init()

一。在

^{pr2}$

一。在

    if stats1['chime'] == 'on':
        playSound(rainbowPip, -1, 0, 200)
    elif stats1['chime'] == 'off':
        stopSound(rainbowPip)

谢谢。在


Tags: 代码游戏init地方prepygame速度我会
1条回答
网友
1楼 · 发布于 2024-10-05 15:21:40

音频的速度可以通过改变采样率来改变。对于一个典型的wav文件,它可以是44100,可以加倍或减半来加速或减速。在

我没有你完整的代码,所以我创建了一个演示代码来解释这个概念。 在这里,输入音频文件piano.wav首先以正常速度播放,然后使其以两倍于原始速度运行。 请注意使用小于1的转换系数来减慢速度的选项。在

希望你能在你的程序中使用这些代码。在

演示代码

import pygame, wave, time

def checkifComplete(channel):
    while channel.get_busy():     #Check if Channel is busy
        pygame.time.wait(800)  #  wait in ms
    channel.stop()

#Set speedUp / Slowdown Factor
#ChangeRATE = 0.5  # set <1 to slow down audio
ChangeRATE = 2    # set >1 to speed up audio


#Define input / output audio files
music_file = "piano.wav"
changed_file = "changed.wav"
swidth = 2

#set up the mixer
freq = 44100     # audio CD quality
bitsize = -16    # unsigned 16 bit
channels = 2     # 1 is mono, 2 is stereo
buffer = 2048    # number of samples

pygame.mixer.init(freq, bitsize, channels, buffer)
pygame.mixer.init()

#Create sound object for Audio
myAudio1 = pygame.mixer.Sound(music_file)

#Create a channel for audio
myChannel1 = pygame.mixer.Channel(1)

#Play Audio
print "Playing audio : ", music_file
myChannel1.play(myAudio1)
checkifComplete(myChannel1) #Check if Audio1 complete

#Open current audio and get parameters
currentSound  = wave.open(music_file, 'rb') #Open input file
sampleRate = currentSound.getframerate()  #Get frame rate
channels = currentSound.getnchannels()  #Get total channels
signal = currentSound.readframes(-1) #Load all frames

#Create new audio with changed parameters
newSound = wave.open(changed_file, 'wb')
newSound.setnchannels(channels)
newSound.setsampwidth(swidth)
print "sampleRate=", sampleRate
newSound.setframerate(sampleRate * ChangeRATE)
sampleRate2 = newSound.getframerate()  #Get new frame rate
print "sampleRate2=", sampleRate2
newSound.writeframes(signal)
newSound.close()

#Create sound object for Changed Audio
myAudio2 = pygame.mixer.Sound(changed_file)

#Create a channel for Changed audio
myChannel2 = pygame.mixer.Channel(2)

#Add changed audio to Channel and Play Changed Audio
print "Playing audio2 : ", changed_file
myChannel2.play(myAudio2)
checkifComplete(myChannel2)

程序输出

^{pr2}$

相关问题 更多 >