I have the next version of pygame package: pygame 2.5.0
(SDL 2.28.0
) in python 3.10.8
.
.ogg file generated by telegram client and uploaded to server is successfully played by VLS application but next python code
import pygame
audio_file_path = r'<OGG PATH>'
pygame.mixer.init()
try:
pygame.mixer.music.load(audio_file_path)
except pygame.error as e:
print("Error:", e)
brings the next error:
Error: stb_vorbis_open_rwops: VORBIS_invalid_first_page
What may be the error reason and what are additional tools that may allow me to check ogg file validity?
When testing your code with my own .ogg
file no errors occured. So this might just be happening to this one file. I can't tell you a reason why this happens, but i can tell you the solutions i found.
Both solutions require downloading a module called pydub
import pygame
from pydub import AudioSegment
from io import BytesIO
def convert_ogg_to_mp3_object(ogg_path):
# Load the OGG file
ogg_audio = AudioSegment.from_ogg(ogg_path)
# Export the OGG audio as MP3 and return the BytesIO object
mp3_object = BytesIO()
ogg_audio.export(mp3_object, format="mp3")
return mp3_object
audio_file_path = r'<OGG PATH>'
file_obj = convert_ogg_to_mp3_object(audio_file_path)
pygame.mixer.init()
pygame.mixer.music.load(file_obj, "")
Here we convert the *.ogg
file to an mp3 file object and lucky for us pygame accepts file objects as seen here.
This solution creates a mp3 file in your system rather than storing a file object.
import pygame
from pydub import AudioSegment
def convert_ogg_to_mp3(ogg_path, mp3_path):
# Load the OGG file
ogg_audio = AudioSegment.from_ogg(ogg_path)
# Export the OGG file as MP3 to the specified path
ogg_audio.export(mp3_path, format="mp3")
audio_file_path = r'<OGG PATH>'
output_file = "<OUTPUT PATH>"
convert_ogg_to_mp3(audio_file_path, output_file)
pygame.mixer.init()
pygame.mixer.music.load("out.mp3", "mp3")
Both solutions work, but the first solution runs just a bit faster than the second. So if you are looking for performance i would suggest the first solution.
If there's a need to convert other files to .mp3
or back to .ogg
pydub can do it.