在Pygam的两个正在进行的音乐曲目之间淡入

2024-06-16 12:33:57 发布

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

我的目的是让两个性质相似的音乐曲目在不同的时间彼此淡出。当出现这种淡入时,一个音乐曲目应在短时间内从全音量变为静音,同时,另一个曲目应从0变为100,并从同一时间索引继续播放。他们必须能够在任何时候动态地进行这项工作,当某个动作发生时,会出现淡入,新的音轨将在另一个音轨停止的同一位置开始播放。在

通过使用音量控制或启动和停止音乐(但是,似乎只有“淡出”选项存在,并且缺少“淡入”选项),这可能是合理的。我该怎么做?如果有的话,最好的方法是什么?如果无法使用Pygame,可以接受Pygame的替代品。在


Tags: 方法目的音乐选项时间动态静音pygame
3条回答

这并不完全是对这个问题的答案,但对于未来的谷歌人,我写了一个脚本,让我早上从第0卷开始的音乐中淡出,这就是我使用的:

max_volume = 40 
current_volume = 0

# set the volume to the given percent using amixer
def set_volume_to(percent):
    subprocess.call(["amixer", "-D", "pulse", "sset", "Master", 
                     str(percent) + "%", "stdout=devnull"])

# play the song and fade in the song to the max_volume 
def play_song(song_file):
    global current_volume
    print("Song starting: " + song_file)
    pygame.mixer.music.load(song_file)
    pygame.mixer.music.play()

    # gradually increase volume to max
    while pygame.mixer.music.get_busy():
        if current_volume < max_volume: 
            set_volume_to(current_volume)
            current_volume += 1

        pygame.time.Clock().tick(1)

 play_song("foo.mp3")

试试这个,挺直截了当的。。在

import pygame

pygame.mixer.init()
pygame.init()

# Maybe you can subclass the pygame.mixer.Sound and
# add the methods below to it..
class Fader(object):
    instances = []
    def __init__(self, fname):
        super(Fader, self).__init__()
        assert isinstance(fname, basestring)
        self.sound = pygame.mixer.Sound(fname)
        self.increment = 0.01 # tweak for speed of effect!!
        self.next_vol = 1 # fade to 100 on start
        Fader.instances.append(self)

    def fade_to(self, new_vol):
        # you could change the increment here based on something..
        self.next_vol = new_vol

    @classmethod
    def update(cls):
        for inst in cls.instances:
            curr_volume = inst.sound.get_volume()
            # print inst, curr_volume, inst.next_vol
            if inst.next_vol > curr_volume:
                inst.sound.set_volume(curr_volume + inst.increment)
            elif inst.next_vol < curr_volume:
                inst.sound.set_volume(curr_volume - inst.increment)

sound1 = Fader("1.wav")
sound2 = Fader("2.wav")
sound1.sound.play()
sound2.sound.play()
sound2.sound.set_volume(0)

# fading..
sound1.fade_to(0)
sound2.fade_to(1)


while True:
    Fader.update() # a call that will update all the faders..

伪代码:

track1 = ...
track2 = ...

track1.play_forever()
track1.volume = 100
track2.play_forever()
track2.volume = 0

playing = track1
tracks = [track1, track2]


def volume_switcher():
    while True:
        playing.volume = min(playing.volume + 1, 100)

        for track in tracks:
            if track != playing:
                track.volume = max(track.volume - 1, 100)

        time.sleep(0.1)

Thread(target=volume_switcher).start()

相关问题 更多 >