仿照darling8611的下载基本上实现了试听功能。
首先在MainWindow里
menuitem = gtk.MenuItem('试听')
menuitem.connect('activate', self.listen)
popupmenu.append(menuitem)
然后定义listen函数
def listen(self, widget):
thread.start_new_thread(self._songlist.listen, (self.path
[0],))
_songlist是List类型的,于是在gmbox.py里List类增加listen函数,如果存在,用mpg123播放,否则,看Listen
对象
def listen(self,i=0):
song=self.songlist[i]
local_uri=song['title']+'-'+song['artist']+'.mp3'
if os.path.exists(local_uri):
os.system('pkill mpg123;mpg123 '+local_uri)
return
songurl="
http://www.google.cn/music/top100/musicdownload?
id="+song['id']
s=SongParser()
try:
text = urllib2.urlopen(songurl).read()
except:
print "Reading URL Error: %s" % local_uri
return
s.feed(text)
Listen(s.url,local_uri)
Listen对象和Download对象很相似,多了线程,一个用于下载块,一个用于播放。播放前用mid3iconv进行乱码转换。由于用线程,开头
还要加上import thread
class Listen:
def __init__(self, remote_uri, local_uri):
self.remote_uri= remote_uri
self.local_uri=local_uri
thread.start_new_thread(self.download,(local_uri,))
time.sleep(1)
thread.start_new_thread(
self.play,(local_uri,))
def play(self,a):
os.system('mid3iconv -e gbk '+self.local_uri+'.cache')
os.system('pkill mpg123')
os.system('mpg123 '+self.local_uri+'.cache')
os.rename(self.local_uri+'.cache', self.local_uri)
def download(self,a):
print u'正在缓冲:',self.local_uri
self.T=self.startT=time.time()
(self.D,self.speed)=(0,0)
urllib.urlretrieve(self.remote_uri, self.local_uri
+'.cache', self.update_progress)
os.rename(self.local_uri+'.cache', self.local_uri
+'.cache')
speed=os.stat(self.local_uri).st_size/(time.time()-
self.startT)
print '\r['+''.join(['=' for i in range(50)])+ \
'] 100.00%% %s/s '%sizeread(speed)
def update_progress(self, blocks, block_size, total_size):
if total_size>0 :
percentage = float(blocks) / (total_size/block_size+1) *
100
if int(time.time()) != int(self.T):
self.speed=(blocks*block_size-self.D)/(time.time()-
self.T)
(self.D,self.T)=(blocks*block_size,time.time())
print '\r['+''.join(['=' for i in range((int)(percentage/
2))])+'>'+ \
''.join([' ' for i in range((int)(50-percentage/2))])+
\
('] %0.2f%% %s/s ' % (percentage,sizeread
(self.speed))),
然后就可以"试听"了...
这样的代码很冗余吧?期待大家优化。。。
还有google music上的单曲试听列表,如果也能够得到就好了。