我怎样才能在pygame中播放声音?

时间:2018-02-05 20:50:26

标签: python python-3.x audio pygame

基本上,我想在这里完成的是一种在游戏运行时平移声音的方法。我想让音量(左和右)根据播放器的位置而改变。现在我有一个简单的代码,我认为这将是一个很好的测试:

pygame.mixer.init()

self.sound = pygame.mixer.Sound("System Of A Down - DDevil #06.mp3")
print("I could get here")
self.music = self.sound.play()

self.music.set_volume(1.0, 0)

首先,我尝试过与pygame.mixer.music类似的东西,但我开始意识到没有办法以这种方式单独更改卷,或者我认为,然后我改为提供的代码这里。 现在好像文件无法加载,我的猜测是文件太大而不能被视为pygame中的声音。知道我如何才能使这项工作?

3 个答案:

答案 0 :(得分:2)

您可以像这样平移频道:

from os import split, join
import pygame
import pygame.examples.aliens
pygame.init()
# get path to an example punch.wav file that comes with pygame.
sound_path = join(split(pygame.examples.aliens.__file__)[0], 'data', 'punch.wav')
sound = pygame.mixer.Sound(sound_path)
# mixer can mix several sounds together at once.
# Find a free channel to play the sound on.
channel = pygame.mixer.find_channel()
# pan volume full loudness on the left, and silent on right.
channel.set_volume(1.0, 0.0)
channel.play(sound)

https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Channel

答案 1 :(得分:1)

为此可能值得研究一个单独的音频库。一般来说,我建议 PortAudio (这是C),但是使用PyAudio提供的python绑定。这样可以更好地控制确切的音频流。

为了进一步简化这一点,有一个名为 PyDub 的库,它构建在PyAudio的顶层,用于高级接口(甚至还有一个特定的pan方法!)。 / p>

from pydub import AudioSegment
from pydub.playback import play

backgroundMusic = AudioSegment.from_wav("music.wav")

# pan the audio 15% to the right
panned_right = backgroundMusic.pan(+0.15)

# pan the audio 50% to the left
panned_left = backgroundMusic.pan(-0.50)

#Play audio
while True:
    try:
       play(panned_left)
      #play(panned_right)

如果这太慢或者没有提供有效的实时实现,那么我肯定会给PyAudio一个机会,因为你还将学习更多关于音频处理的过程!

PS。如果您确实使用PyAudio,请务必查看callback techniques,以便您运行的游戏可以继续使用不同的threads并行运行。

答案 2 :(得分:0)

This answer 当然可以帮助您。

基本上,您获得屏幕宽度,然后根据 master 向左平移,然后根据 player.pos.x / screen_width 向右平移:


伪代码:

1 - player.pos.y / screen_width

文档: