Pygame播放mp3太快(无论我定义的是什么频率)

时间:2013-12-14 13:25:45

标签: pygame

我正在播放一个mp3文件,我在谷歌翻译请求后得到了。当我通过pygame播放时,无论我在pygame.mixer.init()

中设置的频率如何,它都以两倍的速度播放

以下是代码:

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)

很抱歉,如果那里有很多无关紧要的东西,但我认为它可能有用。

2 个答案:

答案 0 :(得分:0)

您应该在mixer.init()之前致电pygame.init(),因为pygame.init()也在初始化调音台。

如果您必须在mixer.init()首次致电pygame.init()后致电mixer.quit()

全是in the docs:)。

答案 1 :(得分:0)

我明白了:

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