When developing games using python, we will inevitably use the pyGame module, which has a sound function. Using this function, we can add sound effects to our games.
Problem Description:
To use the sound module, we must initialize our game at the beginning of the main function, so we add the following statement at the beginning of the main function to initialize the game.
# Game initialization
pygame.init()
However, when I run the program, I find that the game window flashes back and an error message appears, as follows:
D:GameTankWarvenvScriptspython.exe D:/Game/TankWar/main.py
pygame 2.0.2 (SDL 2.0.16, Python 3.8.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "D:/Game/TankWar/main.py", line 41, in <module>
is_quit_game = run_Game(config)
File "D:/Game/TankWar/main.py", line 22, in run_Game
sounds[key] = pygame.mixer.Sound(value)
pygame.error: mixer not initialized
Process finished with exit code 1
it says I didn’t initialize the mixer!!! We can’t help it. Let’s go according to his error report and initialize the mixer separately.
pygame.init()
pygame.mixer.init()
The following error message still appears, and the game window still flashes back.
D:GameTankWarvenvScriptspython.exe D:/Game/TankWar/main.py
pygame 2.0.2 (SDL 2.0.16, Python 3.8.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "D:/Game/TankWar/main.py", line 42, in <module>
is_quit_game = run_Game(config)
File "D:/Game/TankWar/main.py", line 17, in run_Game
pygame.mixer.init()
pygame.error: WASAPI can't find requested audio endpoint: Could not find the element.
Process finished with exit code 1
Solution:
After repeated tests, I found that it can run normally sometimes, and the above error reports will appear sometimes. Finally, I found a big man’s article and solved this problem.
earphone problem
Because I use a desktop computer and have no audio connected, there has been no audio output device, which causes pyGame to not know where to output the sound (in this case, the audio device cannot be found), resulting in an error. After inserting the audio device (i.e. my headset), it’s solved…
#python #audio #pygame
Вопрос:
Я только что запустил небольшой игровой проект и пытаюсь заставить его воспроизводить звук при каждом выстреле пули, но я продолжаю получать ту же ошибку:
pygame.error: mixer system not initialized
Я не понимаю, что я сделал неправильно, поэтому вот мой код:
import pygame, sys
from pygame.locals import *
theClock = pygame.time.Clock()
sound = pygame.mixer.Sound("bullet.mp3")
….
if event.type == KEYDOWN:
if event.key == K_SPACE and shot_count == 0:
sound.play()
shot_y = h-50
shot_x = x
elif event.type == K_SPACE and shot_count == 1:
shot_y_2 = h-50
shot_x_2 = x
print(h, ' ', shot_y, shot_count)
if event.type == KEYUP:
if event.key == K_SPACE and shot_count == 0:
resetShot = 0
elif event.type == K_SPACE and shot_count == 1:
resetShot = 0
Ответ №1:
Вам необходимо pygame.init()
перед использованием объектов микшера / звука.
Согласно документации, вы должны использовать звуковые файлы OGG или WAV.
Комментарии:
1. хорошо, я больше не получаю ошибку, но она не воспроизводит никакого звука
Ответ №2:
Я искал здесь и обнаружил, что pygame
загружаются только OGG и несжатые файлы WAV. Другая проблема заключается в том, что вы забыли инициализировать pygame.mixer
модуль.
pygame.mixer.init()
это самый простой способ инициализации pygame.mixer
модуля.
Для получения дополнительной информации перейдите по предыдущей ссылке.
Комментарии:
1. У меня та же проблема, что и при загрузке моего волнового файла в pygame.mixer.init(), но я продолжаю получать эту ошибку, аудиоустройство не найдено
Ответ №3:
Я делал игру в Тетрис до двух недель, и у меня была та же проблема! Что я сделал, так это вставил это перед воспроизведением звука, и это сработало.
pygame.mixer.init(44100, -16,2,2048)
Попробуйте сами и посмотрите, работает ли это! Я надеюсь, что это помогло
Ответ №4:
Этого достаточно
import pygame as pg
from pygame import mixer
pg.init()
#...
mixer.music.load('sounds/bgsound.mp3')
mixer.music.play(-1)
Ответ №5:
Я столкнулся с той же ошибкой в том же проекте при использовании pycharm в моей системе Linux.
Простой обходной путь — запустить sript в оболочке python или из IDLE (что практически одно и то же).
Если вы такой же пользователь Linux, как и я (я использую Ubuntu), просто откройте папку, содержащую скрипт в терминале, и запустите скрипт с помощью python, например:
python3 Space_Invaders.py
И он должен работать без каких-либо ошибок. Я попытался запустить код без инициализации микшера, используя python IDLE, и там тоже не обнаружил ошибок.
Поэтому я загружаю звуки в свою игру, но получаю эту ошибку Я использую python 3 windows 10
pygame.error: mixer not initialized
Я пробовал ставить, но когда ставлю, получаю
pygame.mixer.init()
Когда я помещаю pygame.mixer.init (), я получаю эту ошибку ?? мне нужно что-то импортировать ??
pygame.error: DirectSoundCreate: No audio device found
import pygame
import math
pygame.init()
pygame.mixer.init()
# window
window = pygame.display.set_mode((800,800))
pygame.display.set_caption("new World")
#
# error bloccks
erblock = pygame.image.load("error.png")
# trees images
treo = pygame.image.load("tree.png")
# mountains
mounto = pygame.image.load("mount.png")
# platform images
blocks = pygame.image.load("block.png")
# coins image
heart = pygame.image.load("heart.png")
# heart image
heartingss = pygame.image.load("health.png")
# define the shooting sound for the player ------------------------
shootsound = pygame.mixer.Sound("ss.wav")
# hit enemy sound
hitenemysound = pygame.mixer.Sound("hitenemy.wav")
# sound for jumping
jumpsound = pygame.mixer.Sound("sjump.wav")
# pick up coins sound
coinssound = pygame.mixer.Sound("coinssound.wav")
# shoot sound
shots = pygame.mixer.Sound("shootsound.wav")
# hit the ice sound
icehit = pygame.mixer.Sound("h.wav")
# health power UP
powerup = pygame.mixer.Sound("pw.wav")
# load this sound if the player is dead
death = pygame.mixer.Sound("death.wav")
# walking sound
walk = pygame.mixer.Sound("walks.wav")
# background music
music = pygame.mixer.Sound("backgroundsong.wav")
pygame.mixer.music.play(-1)
1 ответ
Лучший ответ
Я также столкнулся с похожими ошибками, как показано:
pygame.error: WASAPI can't find requested audio endpoint: Element not found.
Я понял, что забыл подключить наушники к своему рабочему столу, что означает, что на рабочем столе нет устройства вывода звука. Это приводит к тому, что pygame не знает, куда выводить звук (в вашем случае невозможно найти аудиоустройство), что приводит к возникновению ошибок.
После подключения аудиоустройства (например, моих наушников) он работает как шарм!
1
Ben Woo
14 Авг 2020 в 19:00
-
SKrishnan2006
- Posts: 6
- Joined: Thu Jan 07, 2021 3:02 am
Pygame Mixer Not Available
I am trying to use Pygame Mixer to play a sound from an mp3 file. When I do so, I get this error:
Code: Select all
NotImplementedError: mixer module not available (ImportError: libSDL2_mixer-2.0.so.0: cannot open shared object file: No such file or directory)
This happens when whenever I am calling
I have tried following the instructions here: https://github.com/snipsco/snipsmanager/issues/35 but to no avail.
Any help is appreciated. Thank You in advance!
-
B.Goode
- Posts: 14699
- Joined: Mon Sep 01, 2014 4:03 pm
- Location: UK
Re: Pygame Mixer Not Available
Mon Feb 01, 2021 7:55 am
SKrishnan2006 wrote: ↑
Mon Feb 01, 2021 1:44 am
I am trying to use Pygame Mixer to play a sound from an mp3 file. When I do so, I get this error:Code: Select all
NotImplementedError: mixer module not available (ImportError: libSDL2_mixer-2.0.so.0: cannot open shared object file: No such file or directory)
This happens when whenever I am calling
I have tried following the instructions here: https://github.com/snipsco/snipsmanager/issues/35 but to no avail.
Any help is appreciated. Thank You in advance!
Maybe your queries would attract knowledgeable comment if you included details of what model of RPI board you are using, and what Operating System it is running. Along with any other relevant information such as post-installation configuration or modification..
-
SKrishnan2006
- Posts: 6
- Joined: Thu Jan 07, 2021 3:02 am
Re: Pygame Mixer Not Available
Mon Feb 01, 2021 4:15 pm
B.Goode wrote: ↑
Mon Feb 01, 2021 7:55 am
SKrishnan2006 wrote: ↑
Mon Feb 01, 2021 1:44 am
I am trying to use Pygame Mixer to play a sound from an mp3 file. When I do so, I get this error:Code: Select all
NotImplementedError: mixer module not available (ImportError: libSDL2_mixer-2.0.so.0: cannot open shared object file: No such file or directory)
This happens when whenever I am calling
I have tried following the instructions here: https://github.com/snipsco/snipsmanager/issues/35 but to no avail.
Any help is appreciated. Thank You in advance!
Maybe your queries would attract knowledgeable comment if you included details of what model of RPI board you are using, and what Operating System it is running. Along with any other relevant information such as post-installation configuration or modification..
I am using a Raspberry Pi 4, running the latest version of Debian Buster. I haven’t configured any system settings after the install or modified it in any way. I am using a Virtualenv of Python 3.7, and the commands I used are `pip install pygame`.
-
SKrishnan2006
- Posts: 6
- Joined: Thu Jan 07, 2021 3:02 am
Re: Pygame Mixer Not Available
Mon Feb 01, 2021 4:21 pm
rpiMike wrote: ↑
Mon Feb 01, 2021 4:16 pm
If using Python3 that should be ‘pip3 install pygame’
I am using a virtualenv, so I am using `pip` instead of `pip3`, since there is only one python installed in the virtualenv. I am pretty sure this is not the problem, because I have been using pip instead of pip3 many times before. Additionally, I get the `Welcome to Pygame` message as soon as I import it, the error only occurs when mixer is initialized. Therefore, it shouldn’t be an issue with using `pip` instead of `pip3`.
-
SKrishnan2006
- Posts: 6
- Joined: Thu Jan 07, 2021 3:02 am
Re: Pygame Mixer Not Available
Mon Feb 01, 2021 4:23 pm
rpiMike wrote: ↑
Mon Feb 01, 2021 8:14 am
Post some complete code that reproduces the error so that others can try the same.
The code is similar to this:
Code: Select all
from pygame import mixer
mixer.init()
# There is some code here that saves text into an mp3 file
mixer.music.load("voice.mp3") # voice.mp3 plays fine using the Music Player on RPi4
mixer.music.play()
-
B.Goode
- Posts: 14699
- Joined: Mon Sep 01, 2014 4:03 pm
- Location: UK
Re: Pygame Mixer Not Available
Mon Feb 01, 2021 4:57 pm
SKrishnan2006 wrote: ↑
Mon Feb 01, 2021 4:23 pm
rpiMike wrote: ↑
Mon Feb 01, 2021 8:14 am
Post some complete code that reproduces the error so that others can try the same.The code is similar to this:
Code: Select all
from pygame import mixer mixer.init() # There is some code here that saves text into an mp3 file mixer.music.load("voice.mp3") # voice.mp3 plays fine using the Music Player on RPi4 mixer.music.play()
Something similar seems to have been resolved on StackOverflow recently — https://stackoverflow.com/questions/659 … -available
Installing libsdl2-mixer-2.0-0 alone appears to be sufficient to allow pygame.mixer.init() to complete without error.
-
SKrishnan2006
- Posts: 6
- Joined: Thu Jan 07, 2021 3:02 am
Re: Pygame Mixer Not Available
Mon Feb 01, 2021 5:03 pm
B.Goode wrote: ↑
Mon Feb 01, 2021 4:57 pm
SKrishnan2006 wrote: ↑
Mon Feb 01, 2021 4:23 pm
rpiMike wrote: ↑
Mon Feb 01, 2021 8:14 am
Post some complete code that reproduces the error so that others can try the same.The code is similar to this:
Code: Select all
from pygame import mixer mixer.init() # There is some code here that saves text into an mp3 file mixer.music.load("voice.mp3") # voice.mp3 plays fine using the Music Player on RPi4 mixer.music.play()
Something similar seems to have been resolved on StackOverflow recently — https://stackoverflow.com/questions/659 … -available
Installing libsdl2-mixer-2.0-0 alone appears to be sufficient to allow pygame.mixer.init() to complete without error.
WOW that worked! Thanks a lot!
Return to “Python”