所以我在pygame中制作游戏,我的问题是某种声音效果会以不同的速度播放。据我所知,它只会播放两种速度,有时它会正常播放,而另一次它可能会播放得更快。
以下是我的代码的一些部分,我会包含更多,但我无法想象问题可能出现在其他任何地方。知道是什么导致这个吗?
pygame.mixer.pre_init(44000, -16, 2, 512)
pygame.mixer.init()
pygame.init()
rainbowPip = pygame.mixer.Sound('snakey_files/sounds/score up.ogg')
allPips = [redPip,gldPip,dmdPip,crashPip,btnPip,objPip,rainbowPip]
playSound = pygame.mixer.Sound.play
stopSound = pygame.mixer.Sound.stop
if stats1['chime'] == 'on':
playSound(rainbowPip, -1, 0, 200)
elif stats1['chime'] == 'off':
stopSound(rainbowPip)
感谢。
答案 0 :(得分:1)
通过改变采样率可以改变音频速度。对于典型的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)
节目输出
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Playing audio : piano.wav
sampleRate= 44100
sampleRate2= 88200
Playing audio2 : changed.wav
>>>