Pygame error unable to open file

Environment: Operating system: Arch Linux Python version : 2.7.18 SDL version: 2.0.12 PyGame version: 2.0.0 Current behavior: Loading an MP3 file with pygame.mixer.Sound() raises pygame.error Expec...

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

DeclanHoare opened this issue

Dec 16, 2020

· 9 comments

Comments

@DeclanHoare

Environment:

  • Operating system: Arch Linux
  • Python version : 2.7.18
  • SDL version: 2.0.12
  • PyGame version: 2.0.0

Current behavior:

Loading an MP3 file with pygame.mixer.Sound() raises pygame.error

Expected behavior:

It loads the sound without error, like when using an OGG or WAV file

Steps to reproduce:

  1. place test.mp3 in working directory
  2. run test.py

test.zip

Test code

import pygame
pygame.init()
pygame.mixer.Sound("test.mp3")

Stack trace/error output/other error logs

pygame 2.0.0 (SDL 2.0.12, python 2.7.18)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    pygame.mixer.Sound("test.mp3")
pygame.error

@ankith26

Thanks for the report.
The kind of error it’s giving, makes me think that Pygame thinks that SDL errored, when it didn’t

@illume

Thanks @DeclanHoare

Is this with the arch pygame, or the binary pygame from pip/pypi?

@illume

  • Seems we don’t have an mp3 Sound('test.mp3') test, only a mixer.music.load mp3 loading unit test.
  • it could also be that particular mp3 file is not compatible with pygame.

@DeclanHoare

Is this with the arch pygame, or the binary pygame from pip/pypi?

From pypi

it could also be that particular mp3 file is not compatible with pygame.

I have tried a couple, generated with audacity and ffmpeg and they all have the same error.

@DeclanHoare

Is this with the arch pygame, or the binary pygame from pip/pypi?

Although, I had been using the arch version for python 3 where I didn’t have the problem. I’ve just tried the pypi version for python 3 and get a similar error, except that there is now a message.

pygame 2.0.0 (SDL 2.0.12, python 3.9.0)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "/home/declan/Downloads/test/test.py", line 3, in <module>
    pygame.mixer.Sound("test.mp3")
pygame.error: Unable to open file 'test.mp3'

@DeclanHoare
DeclanHoare

changed the title
Cannot load MP3s with Sound() on Python 2

Cannot load MP3s with Sound()

Dec 17, 2020

@ankith26

I am inclined to think that it is an SDL issue. Haven’t done much research on it, but found this in the changelog of the most recent SDL_Mixer version (2.0.5, which hasn’t been released yet)

David Gow - Fri Oct 23 23:01:00 2020
 * Fixed mp3 file detection.

@llindstrom

The SDL2 mixer library shipped with the linux wheel is not built with mp3 support. SDL2-mixer needs either the mad or the mpg123 library to decode mp3. I suggest the mpg123 library as it has the requisite LGPL 2.1 license and is used in the Ubuntu groovy (20.10) build of SDL2-mixer.

@llindstrom

Looking at the SDL2 mixer codec source files I don’t believe SDL ever supported loading an mp3 file as a sound—there is no load_mp3.c file. But SDL supports playing mp3 files through mixer music—see the music_mad.c and music_mpg123.c files. That said, the SDL2 mixer library libSDL2_mixer-2-da0a6e94.0.so.0.2.2 shipped with pygame is not linked to any mp3 decoder library, so no mp3 music support.

@ankith26

MP3 should be supported on Linux now, after pygame v2.0.2, so closing this issue.
If some issues still persist feel free to re-open, or open a new PR

Mandalorec

0 / 0 / 0

Регистрация: 07.12.2019

Сообщений: 26

1

10.06.2020, 08:48. Показов 3781. Ответов 11

Метки нет (Все метки)


Текст ошибки:

Python
1
2
3
4
Traceback (most recent call last):
  File "E:PY19SpaceshipSpaceship.py", line 35, in <module>
    shot = pygame.mixer.Sound('spaceship_shot.mp3')
pygame.error: Unable to open file 'spaceship_shot.mp3'

Возникает при попытке создать новый объект Sound из файла
Если нужна ещё какая-то информация о моём коде скажите

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Модератор

Эксперт Python

2337 / 1401 / 476

Регистрация: 21.02.2017

Сообщений: 3,849

Записей в блоге: 1

10.06.2020, 09:19

2

Цитата
Сообщение от Mandalorec
Посмотреть сообщение

Возникает при попытке создать новый объект Sound из файла

Цитата
Сообщение от Mandalorec
Посмотреть сообщение

Unable to open file ‘spaceship_shot.mp3’

Может ты переведешь текст ошибки?



1



0 / 0 / 0

Регистрация: 07.12.2019

Сообщений: 26

10.06.2020, 09:24

 [ТС]

3

Переводил, пишется:
‘Невозможно открыть файл’ — но почему не могу понять
Файл со звуком лежит в одной папке с программой ,да и сам звук спокойно проигрывается



0



Модератор

Эксперт Python

2337 / 1401 / 476

Регистрация: 21.02.2017

Сообщений: 3,849

Записей в блоге: 1

10.06.2020, 09:28

4

Mandalorec, укажи полный путь к файлу.



1



Mandalorec

0 / 0 / 0

Регистрация: 07.12.2019

Сообщений: 26

10.06.2020, 09:31

 [ТС]

5

Всё равно выдаёт такую же ошибку

Python
1
shot = pygame.mixer.Sound('E:PY19Spaceshipspaceship_shot.mp3')



0



Fudthhh

Модератор

Эксперт Python

2337 / 1401 / 476

Регистрация: 21.02.2017

Сообщений: 3,849

Записей в блоге: 1

10.06.2020, 09:46

6

So pygame only allows for files that are either OGG or a compressed WAV file to be played using Sound. However you can use music instead of sound to play mp3 files.

Python
1
2
3
4
pygame.mixer.music.load("foo.mp3")
pygame.mixer.music.play()
time.sleep(2)
pygame.mixer.music.stop()



2



0 / 0 / 0

Регистрация: 07.12.2019

Сообщений: 26

10.06.2020, 09:56

 [ТС]

7

Понимаешь…мне нужно чтобы звук воспроизводился при выстреле ,тоесть после нажатия кнопки(лкм)
Хотя у меня есть идея…

Добавлено через 9 минут
У меня есть хорошая и две плохие новости
Хорошая — я сделал по твоему примеру и звук стал появляться когда нужно
1 Плохая — time.sleep(2) останавливает всю игру на две секунды
2 Плохая — из за того что теперь у нас как музыка работает выстрел ,другая фоновая музыка перестает играть после первого выстрела



0



Модератор

Эксперт Python

2337 / 1401 / 476

Регистрация: 21.02.2017

Сообщений: 3,849

Записей в блоге: 1

10.06.2020, 10:40

8

Лучший ответ Сообщение было отмечено Mandalorec как решение

Решение

Mandalorec,

Тогда конвертируй трек в нужный формат. В чем проблема то?



1



0 / 0 / 0

Регистрация: 07.12.2019

Сообщений: 26

10.06.2020, 17:05

 [ТС]

9

А это как? То-есть нельзя просто поменять формат файла со звуком?
(Я погуглил и типо нужно через спец сайты?)



0



║XLR8║

1212 / 909 / 270

Регистрация: 25.07.2009

Сообщений: 4,361

Записей в блоге: 5

10.06.2020, 17:07

10



1



Заклинатель змей

611 / 508 / 213

Регистрация: 30.04.2016

Сообщений: 2,412

10.06.2020, 21:41

11

Лучший ответ Сообщение было отмечено Mandalorec как решение

Решение

Mandalorec,

То-есть нельзя просто поменять формат файла со звуком?

Я сейчас положу в бумагу какашки и напишу на ней «шоколад». Станут ли они от этого шоколадом?



1



0 / 0 / 0

Регистрация: 07.12.2019

Сообщений: 26

11.06.2020, 08:01

 [ТС]

12

DobroAlex
Ты поднял мне настроение и объяснил мне смысл конвертации хаха

Спасибо огромное вам всем у меня получилось сделать выстрел после конвертации файла
Я рад



0



Содержание

  1. Pygame error unable to open file
  2. Re: pygame.error: Unable to open file
  3. Re: pygame.error: Unable to open file
  4. Re: pygame.error: Unable to open file
  5. Re: pygame.error: Unable to open file
  6. Pygame.mixer can’t load sound when frozen by Pyinstaller #1514
  7. Comments
  8. Remaining work to do
  9. Double free or corruption loading unusual WAV files #406
  10. Comments
  11. Unable to open PNG file on Raspberry Pi #2503
  12. Comments

Pygame error unable to open file

i have a fresh installing of reapberry pi.

successful install (pip3 install text-to-speech)

the error code says:

Re: pygame.error: Unable to open file

i have a fresh installing of reapberry pi.

successful install (pip3 install text-to-speech)

the error code says:

I think your strategy of asking the developer for assistance via their Github issues page is the correct one.

Re: pygame.error: Unable to open file

i have a fresh installing of reapberry pi.

successful install (pip3 install text-to-speech)

the error code says:

Is /home/pi/Desktop/python/ your current working directory at the time you invoke python3 helloworld.py ?

There seems to be a file playsound.py in that directory which will be read in preference to the installed version.

Try renaming that playsound.py file, and any associated .pyc file, then rerun the test.

Re: pygame.error: Unable to open file

i found out i try to create the same file name in that python directory

Re: pygame.error: Unable to open file

i found out i try to create the same file name in that python directory

Источник

Pygame.mixer can’t load sound when frozen by Pyinstaller #1514

Tested on windows 10.

I tested with pygame 1.9.6 and pygame 2, and it worked in pygame 1.9.6.

Attached is my test code, compiled into executables with pygame 1.9.6 and pygame 2.
mixer_load_test.zip

Remaining work to do

  • install a hook inside pygame so it can find dlls for pyinstaller
  • confirm next pygame release(or master) works with pyinstaller on windows.

The text was updated successfully, but these errors were encountered:

Thank you for reporting this, and for the detailed test case.
It would really help if you also posted which version of Python you used, whicgh PyGame 2.0 preview release, which version of PyInstaller, and what error message you got. I’ll try to reproduce this on Linux, with Python 3.6 and PyInstaller 3.4, and then post my findings.

I have recently looked into the file loading code. It uses the SDL2 RWops. I looked at the SDL2 file loading code too, and it sometimes does «clever» platform-specific things with paths. So possibly, this also depends on the SDL2 version, or it only happens with «» path separators. Maybe not.
@Starbuck5 : please also post the SDL2 version your PyGame uses. For now, I’ll assume you used the compiled windows version of pygame from pip and didn’t compile your own SDL.

Dear contributors/maintainers:
Please check if this bug, or a related bug, happens on different operating systems, with the path dividers changed from «» to «/» if necessary. This might be a bug in PyInstaller, and if it is, we can coordinate here who will report that bug there.

I tested on pygame 2 dev 6, python 3.7.5, and pyinstaller 3.5.
SDL 2.0.10

Line of code with error:
sound = pygame.mixer.Sound(«sounds\explosion1.ogg»)

Error msg:
Unable to open file ‘sounds\\explosion1.ogg’

Источник

Double free or corruption loading unusual WAV files #406

I see hard crashes with a freshly built pygame 1.9.4 when attempting to load WAV sound files with unusual codecs.

The files I’m testing with are here:

I see this crash with wav22kgsm.wav , wav22kulaw.wav , wav8kmp316.wav and wav8kmp38.wav .

I’m building against

To Do to close this:

  • See if these files also fail to load with C code in using latest SDL_mixer.
  • If so report on SDL bugzilla and set this to Difficulty Waiting.
  • Close if SDL_mixer is updated with fixes

The text was updated successfully, but these errors were encountered:

Thanks. There’s a number of people reporting wav issues on stackoverflow.

Here’s the steps needed to proceed.

  1. see if there are bugs already listed against sdl_mixer1/2 (see below).
  2. check if it’s failing with recent SDL2_mixer
  3. a test case using just C sdl_mixer1/2 and the wav files.
  4. perhaps add some code to detect these unsupported formats to include in pygame (if sdl doesn’t fix things). So it can raise an exception.

More distro bug trackers are listed here:

It’s most often the case that one distro can fix things, but not send the fix upstream. So it might already be fixed.

There is one alternate issue with wav files I’ve seen and its that pygame will flat-out reject wav files that do not have a 16-bit pcm bitrate. Lots of people go to stackoverflow after getting sounds from freesound.org or others that have an 8-bit or a 32-bit pcm bitrate and are confused about why it isn’t working. I have no knowledge of C/C++/SDL so I cant help anywhere, just sharing my experiences.

This is a bug in sdl mixer 1.2.12 the bug and a patch are here https://bugzilla.libsdl.org/show_bug.cgi?id=1418
The latest release of sdl mixer is 1.2.12 but this seems quite old (2013) most packages maintainers have added patches and pygame may need to do the same e.g. arch’s patches https://git.archlinux.org/svntogit/packages.git/tree/trunk?h=packages/sdl_mixer
It should be possible to add the patch to the manylinux wheel build. I don’t know what the best approach would be — I’d be happy to help though.

@tonysimpson thanks for the offer 🙂

We build sdl_mixer for the wheels ourselves for windows, mac, and manylinux. It should be possible to fairly easily apply the patch on the mac and manylinux builds.

For mac we use the homebrew stuff. In the sdl_mixer.rb formula they do not apply any patches.
/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/Formula/sdl_mixer.rb We already have a repo for a change to portmidi here: https://github.com/pygame/homebrew-portmidi So it’s possible to copy that formula into our repo and apply patches to sdl_mixer. Also, you can submit a pr to homebrew sdl_mixer so that our mod won’t be necessary in the future.

For windows, building the dependencies is. a challenge, and complicated.

Источник

Unable to open PNG file on Raspberry Pi #2503

Environment:

  • Operating system: Linux(Debian — Raspberry Pi OS 32bit)
  • Python version: 3.7.3
  • SDL version: SDL 2.0.9
  • PyGame version: 2.0.1
  • Relevant hardware: Raspberry Pi 3B+

Current behavior:

When I run some code that loads in a PNG image on the raspberry pi, it doesn’t work (complains about it not being a Windows BMP file). This is not the case when I run the code on my laptop (x86_64) in both Linux(Linux Mint 20.1) and Windows 10.

It may be something I don’t know about or to do with the OS, but I’m not really sure.

Expected behavior:

The images are loaded just like on other platforms

Steps to reproduce:

Please explain the steps required to duplicate the issue, especially if you are able to provide a sample application.
if the bug is caused by a specific file (image, font, sound, level, please upload it as an attachment

  1. Run the test code below
  2. Use a PNG file, any will do (below is one I have verified to cause the error)

Test code

If possible add a simple test program that shows the problem described in this report.

Stack trace/error output/other error logs

The text was updated successfully, but these errors were encountered:

Источник

007fred50

Posts: 6
Joined: Wed Apr 01, 2020 9:37 am

pygame.error: Unable to open file

Hello,

i have a fresh installing of reapberry pi.

Code: Select all

No LSB modules are available.
Distributor ID:	Raspbian
Description:	Raspbian GNU/Linux 10 (buster)
Release:	10
Codename:	buster

but then i try to install (https://pypi.org/project/text-to-speech/)

successful install (pip3 install text-to-speech)

Code: Select all

from text_to_speech import speak 

speak("hello")

python3 helloworld.py

the error code says:

Code: Select all

pygame 1.9.4.post1
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "helloworld.py", line 1, in <module>
    from text_to_speech import speak 
  File "/home/pi/.local/lib/python3.7/site-packages/text_to_speech/__init__.py", line 1, in <module>
    from .text_to_speech import (
  File "/home/pi/.local/lib/python3.7/site-packages/text_to_speech/text_to_speech.py", line 3, in <module>
    from playsound import playsound
  File "/home/pi/Desktop/python/playsound.py", line 5, in <module>
    Sound = pygame.mixer.Sound('//home/pi/Desktop/python/speech09022021212808.mp3')
pygame.error: Unable to open file '//home/pi/Desktop/python/speech09022021212808.mp3'

can you help me out?


User avatar

B.Goode

Posts: 14693
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: pygame.error: Unable to open file

Wed Feb 10, 2021 2:37 pm

007fred50 wrote: ↑

Wed Feb 10, 2021 1:41 pm


Hello,

i have a fresh installing of reapberry pi.

Code: Select all

No LSB modules are available.
Distributor ID:	Raspbian
Description:	Raspbian GNU/Linux 10 (buster)
Release:	10
Codename:	buster

but then i try to install (https://pypi.org/project/text-to-speech/)

successful install (pip3 install text-to-speech)

Code: Select all

from text_to_speech import speak 

speak("hello")

python3 helloworld.py

the error code says:

Code: Select all

pygame 1.9.4.post1
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "helloworld.py", line 1, in <module>
    from text_to_speech import speak 
  File "/home/pi/.local/lib/python3.7/site-packages/text_to_speech/__init__.py", line 1, in <module>
    from .text_to_speech import (
  File "/home/pi/.local/lib/python3.7/site-packages/text_to_speech/text_to_speech.py", line 3, in <module>
    from playsound import playsound
  File "/home/pi/Desktop/python/playsound.py", line 5, in <module>
    Sound = pygame.mixer.Sound('//home/pi/Desktop/python/speech09022021212808.mp3')
pygame.error: Unable to open file '//home/pi/Desktop/python/speech09022021212808.mp3'

can you help me out?

I think your strategy of asking the developer for assistance via their Github issues page is the correct one.


User avatar

B.Goode

Posts: 14693
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: pygame.error: Unable to open file

Wed Feb 10, 2021 3:30 pm

007fred50 wrote: ↑

Wed Feb 10, 2021 1:41 pm


Hello,

i have a fresh installing of reapberry pi.

Code: Select all

No LSB modules are available.
Distributor ID:	Raspbian
Description:	Raspbian GNU/Linux 10 (buster)
Release:	10
Codename:	buster

but then i try to install (https://pypi.org/project/text-to-speech/)

successful install (pip3 install text-to-speech)

Code: Select all

from text_to_speech import speak 

speak("hello")

python3 helloworld.py

the error code says:

Code: Select all

pygame 1.9.4.post1
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "helloworld.py", line 1, in <module>
    from text_to_speech import speak 
  File "/home/pi/.local/lib/python3.7/site-packages/text_to_speech/__init__.py", line 1, in <module>
    from .text_to_speech import (
  File "/home/pi/.local/lib/python3.7/site-packages/text_to_speech/text_to_speech.py", line 3, in <module>
    from playsound import playsound
  File "/home/pi/Desktop/python/[b]playsound.py[/b]", line 5, in <module>
    Sound = pygame.mixer.Sound('//home/pi/Desktop/python/speech09022021212808.mp3')
pygame.error: Unable to open file '//home/pi/Desktop/python/speech09022021212808.mp3'

can you help me out?

Is /home/pi/Desktop/python/ your current working directory at the time you invoke python3 helloworld.py ?

There seems to be a file playsound.py in that directory which will be read in preference to the installed version.

Try renaming that playsound.py file, and any associated .pyc file, then rerun the test.






Return to “Troubleshooting”

Уведомления

  • Начало
  • » Python для новичков
  • » Проблема с воспроизведением MP3 файлов

#1 Июнь 12, 2020 13:40:31

Проблема с воспроизведением MP3 файлов

Нашел на одном форуме код для воспроизведения MP3 файлов:

 pygame.init()
song = pygame.mixer.Sound('Колизей.mp3')
clock = pygame.time.Clock()
song.play()
while True:
    clock.tick(60)
pygame.quit()

Но он не работает, выдает вот такую ошибку:
pygame.error: Unable to open file ‘u041au043eu043bu0438u0437u0435u0439.mp3’

Прошу помочь разобраться, что не так.

Офлайн

  • Пожаловаться

#2 Июнь 12, 2020 17:37:48

Проблема с воспроизведением MP3 файлов

Konstantin1984+ попробуйте для начала имя файла латиницей, чтото мне подсказвает что ваш пайгейм плохо доужит с кирилицей.

==============================
Помещайте код в теги:

Бериегите свое и чужое время.

Офлайн

  • Пожаловаться

#3 Июнь 13, 2020 12:31:28

Проблема с воспроизведением MP3 файлов

Не помогло. А вот формат “wav” открывает без вопросов.

Офлайн

  • Пожаловаться

#4 Июнь 13, 2020 13:29:57

Проблема с воспроизведением MP3 файлов

Konstantin1984+
Не помогло. А вот формат “wav” открывает без вопросов.

аха, а докементацию вы по прежнему игнорируете…
https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.Sound

The Sound can be loaded from an OGG audio file or from an uncompressed WAV.

тоесть Sound не понимает mp3 от слова “совсем”. С mp3 работает pygame.mixer.music .

==============================
Помещайте код в теги:

Бериегите свое и чужое время.

Отредактировано PEHDOM (Июнь 13, 2020 13:41:30)

Офлайн

  • Пожаловаться

#5 Июнь 19, 2020 23:44:51

Проблема с воспроизведением MP3 файлов

Спасибо! Нашел нужный код, порядка четырех строк и можно запускать аудиофайлы разного формата.

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » Проблема с воспроизведением MP3 файлов

Понравилась статья? Поделить с друзьями:
  • Putty network error network is unreachable
  • Pygame error text has zero width
  • Putty network error connection timed out что это 22 порт
  • Pygame error out of memory
  • Pygame error no video mode has been set