运行在raspberry上的多个音频文件

2024-04-20 13:34:00 发布

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

我正在做一个小的家庭项目,我需要能够开始一首歌,然后跟踪它(比如把它保存到一个变量或其他),这样我就可以在不改变其他声音文件的情况下调整某些声音文件的音量。我查过pygame,得到了可以玩的声音文件

import pygame
pygame.mixer.init()
pygame.mixer.music.load("myFile.mp3")
pygame.mixer.music.play()

但有了这首歌,我就不能在不改变第二首歌的情况下,开始另一首歌,调整第一首歌的音量。是否可以将第一首歌曲保存在一个变量中,这样我就可以对它使用set_volume()函数了?在


Tags: 项目importplayinit家庭music情况load
1条回答
网友
1楼 · 发布于 2024-04-20 13:34:00

您可以为每首歌曲设置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)

程序输出

^{pr2}$

相关问题 更多 >