Pygame, sounds don't play

2019-01-13 21:49发布

I'm trying to play sound files (.wav) with pygame but when I start it I never hear anything.
This is the code:

import pygame

pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")

sounda.play()

I also tried using channels but the result is the same

13条回答
Luminary・发光体
2楼-- · 2019-01-13 22:14
import pygame

pygame.init()
sound = pygame.mixer.Sound("desert_rustle.wav")
pygame.mixer.Sound.play(sound)

This will work on python 3

查看更多
干净又极端
3楼-- · 2019-01-13 22:17

For me (on Windows 7, Python 2.7, PyGame 1.9) I actually have to remove the pygame.init() call to make it work or if the pygame.init() stays to create at least a screen in pygame.

My example:

import time, sys
from pygame import mixer

# pygame.init()
mixer.init()

sound = mixer.Sound(sys.argv[1])
sound.play()

time.sleep(5)
查看更多
一纸荒年 Trace。
4楼-- · 2019-01-13 22:19

What you need to do is something like this:

 import pygame
 import time

 pygame.init()
 pygame.mixer.init()
 sounda= pygame.mixer.Sound("desert_rustle.wav")

 sounda.play()
 time.sleep (20)

The reason I told the program to sleep is because I wanted a way to keep it running without typing lots of code. I had the same problem and the sound didn't play because the program closed immediately after trying to play the music.

In case you want the program to actually do something just type all the necessary code but make sure it will last long enough for the sound to fully play.

查看更多
Luminary・发光体
5楼-- · 2019-01-13 22:21

Just try:

import pygame.mixer
from time import sleep
pygame.mixer.init()
pygame.mixer.music.load(open("\windows\media\chimes.wav","rb"))
print ""
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
sleep(1)
print "done"

This should work. You just need to add print ""and the sound will have had time to load its self.

查看更多
虎瘦雄心在
6楼-- · 2019-01-13 22:21

I've had something like this happen. Maybe you have the same problem? Try using an absolute path:

import pygame

pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("/absolute_path/desert_rustle.wav")

sounda.play()

Where abslute_path is obviously replaced with your actual absolute path ;)

good luck.

查看更多
欢心
7楼-- · 2019-01-13 22:23

Your code plays desert_rustle.wav quite fine on my machine (Mac OSX 10.5, Python 2.6.4, pygame 1.9.1). What OS and Python and pygame releases are you using? Can you hear the .wav OK by other means (e.g. open on a Mac's terminal or start on a Windows console followed by the filename/path to the .wav file) to guarante the file is not damaged? It's hard to debug your specific problem (which is not with the code you give) without being able to reproduce it and without having all of these crucial details.

查看更多
登录 后发表回答