Pygame audio game playback speed

quick question.

I run pygame under linux only to play some audio files. I have some .wav files, and I am having problems playing them at the right speed.

import pygame.mixer, sys, time

#plays too fast
pygame.mixer.init(44100)
pygame.mixer.music.load(sys.argv[1])
pygame.mixer.music.play()
time.sleep(5)
pygame.mixer.quit()

#plays too slow
pygame.mixer.init(22100)
pygame.mixer.music.load(sys.argv[1])
pygame.mixer.music.play()
time.sleep(5)
pygame.mixer.quit()

I was looking for some ggogle code, but everyone seems to perfectly call the init function with default parameters. Can other users run this script and see if they get the same behavior or not? Does anyone know how to speed it up? Or adjust the speed for each file?

Thanks.

+6
source share
5 answers

mp3-. , mp3, mutagen :

import pygame, mutagen.mp3

song_file = "your_music.mp3"

mp3 = mutagen.mp3.MP3(song_file)
pygame.mixer.init(frequency=mp3.info.sample_rate)

pygame.mixer.music.load(song_file)
pygame.mixer.music.play()

.

+3

, Audacity. . , .

+2

H. wave.

import wave
import pygame

file_path = '/path/to/sound.wav'
file_wav = wave.open(file_path)
frequency = file_wav.getframerate()
pygame.mixer.init(frequency=frequency)
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()

, frequency , pygame.mixer.init, pygame.mixer.quit. Pygame

+2

If you use Ogg Vorbis encoding (.ogg), the same stuttering sound issue occurs. You will need to read the frequency of what you are trying to reproduce before initializing the mixer object.

Here's how to play .ogg audio at the appropriate frequency using pygame.

from pyogg import VorbisFile
from pygame import mixer

# path to your audio
path = "./file.ogg"
# an object representing the audio, see https://github.com/Zuzu-Typ/PyOgg
sound = VorbisFile(path)
# pull the frequency out of the Vorbis abstraction
frequency = sound.frequency
# initialize the mixer
mixer.init(frequency=frequency)
# add the audio to the mixer music channel
mixer.music.load(path)
# mixer.music.set_volume(1.0)
# mixer.music.fadeout(15)
# play
mixer.music.play()
0
source

All Articles