9

快速提问。

我在 linux 下运行 pygame 只是为了播放一些音频文件。我有一些 .wav 文件,但以正确的速度播放它们时遇到问题。

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()

我已经用 ggogle 代码搜索了一些东西,但似乎每个人都可以使用默认参数调用 init 函数。其他人可以尝试运行此脚本并查看他们是否获得相同的行为吗?有人知道如何加快速度吗?或者调整每个文件的速度?

谢谢。

4

5 回答 5

5

改善Chris 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.quitPygame 文档

于 2017-09-06T13:03:36.000 回答
5

我的一些 mp3 音轨播放速度变慢了。我使用诱变剂将混频器频率更新为基于 mp3 采样率,如下所示:

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()

它解决了这个问题。

于 2017-02-18T16:06:45.863 回答
3

Open your audio file in a free audio tool like Audacity. It will tell you the sampling rate of your media. It will also allow you to convert to a different sampling rate so all your sounds can be the same.

于 2010-01-29T01:55:18.213 回答
2

我想通了...有一个波形模块http://docs.python.org/library/wave.html,它可以读取wav文件的采样率。

于 2010-01-29T20:37:11.730 回答
2

如果您使用的是 Ogg Vorbis (.ogg) 编码,则会出现同样的音频卡顿问题。在初始化混音器对象之前,您必须阅读您尝试播放的频率。

以下是如何使用 pygame 以适当的频率播放 .ogg 音频。

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's music channel
mixer.music.load(path)
# mixer.music.set_volume(1.0)
# mixer.music.fadeout(15)
# play
mixer.music.play()
于 2019-07-15T18:41:04.413 回答