Hello Google Music Beta via Python

It plays randomly one song of all in your Google Music Beta's library. You can listen to the music with a line typing. Have a lot of fun!

Update 07.28.2011

  • changed sound library from pygame to pymedia.

Requirements

  • python (I recommend 2.6.x or higher, but not 3.x.)
  • pygame
  • pymedia
  • simplejson (If your python is lower than 2.5.x.)

Known Issues

  • It's tested in only MP3.
  • It starts to play after downloading entire data. (Not streaming)
  • 'pygame.mixer.quit()' hangs on my PC. (Why?)
administrator@CF-T4 ~ $ uname -a
Linux CF-T4 2.6.35-22-generic #33-Ubuntu SMP Sun Sep 19 20:34:50 UTC 2010 i686 GNU/Linux
administrator@CF-T4 ~ $ dpkg -l|grep "pygame"
ii  python-pygame                         1.9.1release-0ubuntu1                             SDL bindings for games development in Python
administrator@CF-T4 ~ $ python -c "import pymedia;print pymedia.__version__"
1.3.7.0

Usage

administrator@CF-T4 ~ $ ./gmusicplay.py 
./gmusicplay.py EMAIL PASSWD
administrator@CF-T4 ~ $ ./gmusicplay.py someone@gmail.com YourPassword

Source Code of 'gmusicplay.py'

This is MIT License.

#!/usr/bin/env python

import sys,re,time
import urllib,urllib2,cookielib
import xml.dom.minidom
#import cStringIO,random

try:
  import json
except ImportError,e:
  import simplejson as json

#import pygame
import mimetypes,random
import pymedia.audio.acodec
import pymedia.muxer
import pymedia.audio.sound

if len(sys.argv)!=3:
  sys.stderr.write("%s EMAIL PASSWD\n"%sys.argv[0])
  sys.exit(2)

_,email,passwd=sys.argv

urls=[
  "http://music.google.com/",
  "http://music.google.com/music/listen",
  "http://music.google.com/music/services/loadalltracks?u=0&xt=%s",
  "http://music.google.com/music/play?songid=%s&pt=e",
]

cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

res=opener.open(urls[0])
html=re.sub(r"\r|\n"," ",re.sub(r"\s{2,}"," ",res.read()))
form=re.search("<form.*?</form>",html).group()
inputs="\n".join(re.findall("<input .*?/>",form))
dom=xml.dom.minidom.parseString(
  re.match("<form.*?>",form).group()+inputs+"</form>")

urls.append(dom.getElementsByTagName("form")[0].getAttribute("action"))

params={}
for tag in dom.getElementsByTagName("input"):
  params[tag.getAttribute("name")]=tag.getAttribute("value")

params["Email"]=email
params["Passwd"]=passwd

res = opener.open(urls[-1],urllib.urlencode(params))

res = opener.open(urls[1])
xt_cookie=cj._cookies["music.google.com"]["/music"]["xt"]
xt=xt_cookie.value

res = opener.open(urls[2]%xt,urllib.urlencode({"json":"{}"}))
all_tracks = json.loads(res.read())["playlist"]

index=random.randint(0,len(all_tracks)-1)

print "%s / %s"%(all_tracks[index]["title"],all_tracks[index]["artist"])
res = opener.open(urls[3]%all_tracks[index]["id"])

res = opener.open(json.loads(res.read())["url"])
ext=mimetypes.guess_extension(res.headers.gettype())[1:]

snd=dec=None
dm = pymedia.muxer.Demuxer(ext)
s = res.read(1024*200)
while len(s):
  frames = dm.parse(s)
  if not dec:
    dec = pymedia.audio.acodec.Decoder(dm.streams[0])
  for fr in frames:
    r= dec.decode(fr[1])
    if not snd:
      snd= pymedia.audio.sound.Output(r.sample_rate,r.channels,
                                      pymedia.audio.sound.AFMT_S16_LE)
    snd.play(r.data)
  s=res.read(len(s))

"""
audio=cStringIO.StringIO(res.read())

pygame.mixer.pre_init(44100, -16, 2, 1024*3)
pygame.init()
pygame.mixer.music.load(audio)
try:
  pygame.mixer.music.play()
  while pygame.mixer.music.get_busy():
    time.sleep(1)
except KeyboardInterrupt:
  pygame.mixer.music.stop()

pygame.mixer.quit()
pygame.quit()
"""

See Also