我正在做一个小型家庭项目,我需要能够开始播放一首歌曲,然后对其进行跟踪(例如将其保存到变量或其他内容中),以便可以在不更改其他声音文件的情况下调整某些声音文件的音量。我研究了pygame,并获得了要播放的声音文件
import pygame
pygame.mixer.init()
pygame.mixer.music.load("myFile.mp3")
pygame.mixer.music.play()
但与此同时,我无法开始播放另一首歌曲并调整第一首歌曲的音量而不改变第二首歌曲。是否可以将第一首歌曲保存在变量中,以便我可以在其上使用set_volume()函数?
您可以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
>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句