我正在开发一个小型的家庭项目,我需要能够启动一首歌然后跟踪它(比如将它保存到变量或其他东西),这样我就可以调整某些声音文件的音量而无需更改其他声音文件。我查看了pygame,然后我将声音文件与
一起播放import pygame
pygame.mixer.init()
pygame.mixer.music.load("myFile.mp3")
pygame.mixer.music.play()
但有了这个,我无法开始另一首歌并调整第一首歌的音量而不改变第二首歌。是否可以将第一首歌保存在变量中,以便我可以在其上使用set_volume()函数?
答案 0 :(得分:1)
您可以为每首歌设置channels
,为每个频道添加歌曲,然后操纵频道而不是音乐对象。
这是一个有效的代码。对于添加到每个频道的每首歌曲,它会以不同的方式改变音量。该程序假定您当前工作目录中audio
文件夹中的所有歌曲。
该程序过于简化以说明概念。您当然可以创建歌曲和频道列表,然后根据索引添加和操作它们。
<强>程序强>
import pygame
def checkifComplete(channel):
while channel.get_busy(): #Check if Channel is busy
pygame.time.wait(800) # wait in ms
channel.stop() #Stop channel
if __name__ == "__main__":
music_file1 = "sounds/audio1.wav"
music_file2 = "sounds/audio2.wav"
#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 (experiment to get right sound)
pygame.mixer.init(freq, bitsize, channels, buffer)
pygame.mixer.init() #Initialize Mixer
#Create sound object for each Audio
myAudio1 = pygame.mixer.Sound(music_file1)
myAudio2 = pygame.mixer.Sound(music_file2)
#Create a Channel for each Audio
myChannel1 = pygame.mixer.Channel(1)
myChannel2 = pygame.mixer.Channel(2)
#Add Audio to first channel
myAudio1.set_volume(0.8) # Reduce volume of first audio to 80%
print "Playing audio : ", music_file1
myChannel1.play(myAudio1)
checkifComplete(myChannel1) #Check if Audio1 complete
#Add Audio to second channel
myAudio2.set_volume(0.2) # Reduce volume of first audio to 20%
print "Playing audio : ", music_file2
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 : sounds/audio1.wav
Playing audio : sounds/audio2.wav
>>>