Pygame plays mp3 too fast (regardless of what frequency i define)

谁都会走 提交于 2019-12-25 02:32:53

问题


I´m playing an mp3 file I get after a request to google translate. When I play it through pygame it plays at twice the speed, regardless of what frequency I set in pygame.mixer.init()

Here's the code:

import tweepy, urllib, os, pygame, pycurl, difflib, time
pygame.init()
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096) 

consumer_key = 'xxxxxxxxx'
consumer_secret = 'xxxxxxxx'
access_token = 'xxxxxx'
access_token_secret = 'xxxxxx'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

# function to download a file from a url, used for testing
def downloadFile(url, fileName):
    fp = open(fileName, "wb")
    curl = pycurl.Curl()
    curl.setopt(pycurl.URL, url)
    curl.setopt(pycurl.WRITEDATA, fp)
    curl.perform()
    curl.close()
    fp.close()

# returns the appropriate google speech url for a particular phrase
def getGoogleSpeechURL(phrase):
    googleTranslateURL = "http://translate.google.com/translate_tts?tl=en&"
    parameters = {'q': phrase}
    data = urllib.urlencode(parameters)
    googleTranslateURL = "%s%s" % (googleTranslateURL,data)
    return googleTranslateURL

def speakSpeechFromText(phrase):
    googleSpeechURL = getGoogleSpeechURL(phrase.encode('utf-8').strip())
    downloadFile(googleSpeechURL,"tts.mp3")
    pygame.mixer.music.load("tts.mp3")
    pygame.mixer.music.play(0,0.0)
    while pygame.mixer.music.get_busy():
        pygame.time.Clock().tick(10)
    #os.system("mplayer tts.mp3 -af extrastereo=0 &")


def diffindex(string1, string2):
    for i, (char1, char2) in enumerate(zip(string1, string2)):
        if char1 != char2:
            return 1
    return 2

A = "a"
B = "b"

api = tweepy.API(auth)

while(true)
    results = api.search(q="Hackney", count=1, result_type="recent")
    for result in results:
        A = result.text

    if diffindex(A, B) != 2:
        speakSpeechFromText(A)
        B = A
    else:
        print ("jaha")
    time.sleep(20)

Sorry if there´s a lot of irrelevant stuff there as well but I thought it might be of use.


回答1:


I got it:

pygame.mixer.pre_init(16000, -16, 2, 2048) # setup mixer to avoid sound lag
pygame.mixer.init()
pygame.mixer.music.load("mymp3file.mp3")
pygame.mixer.music.play()
# I adjusted the 16000 - it was 44100, tryied 48000, 22000, 110000 and themn 16000



回答2:


You should call the mixer.init() before pygame.init() because pygame.init() also initializing the mixer.

If you have to call mixer.init() after pygame.init() first call mixer.quit().

It's all in the docs :).



来源:https://stackoverflow.com/questions/20583870/pygame-plays-mp3-too-fast-regardless-of-what-frequency-i-define

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!