1

我正在编写一个可以使用 gmusicapi ( https://github.com/simon-weber/Unofficial-Google-Music-API ) 播放音乐、操作播放列表等的界面。我有我的应用程序,以便它可以下载原始 mp3 数据,但我很难找到一个可以播放它的库。GST 可以播放 url,但不允许 cookie 身份验证。pygame 可以播放 mp3,但来自文件,而不是数据。有人知道如何在 python 中播放原始 mp3 数据吗?

def gm_PlaySong(self, url):
    req = urllib2.Request(url)
    for cookie in self.api.session.cookies:
        req.add_header(cookie.name, cookie.value)
    resp = urllib2.urlopen(req)
    song = resp.read()

歌曲是原始的mp3。

4

1 回答 1

0

写入文件

首先,您可以做的简单的事情是将您的 mp3 数据写入一个文件以供 pygame 播放。你可以这样做:

import pygame
def gm_PlaySong(self, url):
    req = urllib2.Request(url)
    for cookie in self.api.session.cookies:
        req.add_header(cookie.name, cookie.value)
    resp = urllib2.urlopen(req)
    song = resp.read()
    with open('path/to/file.mp3', 'wb') as outfile:
        outfile.write(song)
    
    pygame.mixer.music.load('path/to/file.mp3')

使用StringIO

或者,您可以干燥一些东西——这有点猜测,因为我没有在这里测试它的工具——您可以尝试使用StringIO.StringIO该类将原始 mp3 数据提供给 pygame,类似于Python 文件对象会。

这看起来像这样:

import pygame, StringIO
def gm_PlaySong(self, url):
    req = urllib2.Request(url)
    for cookie in self.api.session.cookies:
        req.add_header(cookie.name, cookie.value)
    resp = urllib2.urlopen(req)
    song = StringIO.StringIO(resp.read()) # Gives you a file-like object
    
    # load song
    pygame.mixer.music.load(song)
于 2012-10-15T04:34:22.710 回答