Python实现在线音乐播放器

yipeiwu_com5年前Python基础

最近这几天,学习了一下python,对于爬虫比较感兴趣,就做了一个简单的爬虫项目,使用Python的库Tkinsert做了一个界面,感觉这个库使用起来还是挺方便的,音乐的数据来自网易云音乐的一个接口,通过requests模块,get请求将数据获得,使用Json模块进行数据的解析,最终使用python的mp3play库进行对音乐的在线播放,以下是该程序的源码。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-12-28 21:03:21
# @Author : Donoy (172829352@qq.com)
# @Link : http://www.cnblogs.com/Donoy/
# @Version : $Id$

from Tkinter import *
import tkMessageBox
import requests
import json
import urllib
import mp3play
import threading
import time

def center_window(root, width, height): 
 screenwidth = root.winfo_screenwidth() 
 screenheight = root.winfo_screenheight() 
 size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2) 
 root.geometry(size) 

def createWnd():
 global root
 global listBox
 global text
 
 root = Tk()
 root.title('-----DMPlayer------来自网易云音乐-----')

 center_window(root, 440, 250)

 root['background'] = '#C7EDCC'
 
 text = Entry(font='宋体',width=36)
 text.pack()
 button = Button(root,text='搜索',width=18,fg='red',background='#CDCDC1',command=searchM).pack()
 
 listBox = Listbox(root, height=12,width=72,background='#C7EDCC')
 listBox.bind('<Double-Button-1>',play)
 listBox.pack()

 root.mainloop()

def searchM():
 global m_List 
 itemCount = 50

 if not text.get():
 tkMessageBox.showinfo('温馨提示','您可以输入以下内容进行搜索\n1.歌曲名\n2.歌手名\n3.部分歌词')
 return

 #获得输入的歌名
 url = 'http://s.music.163.com/search/get/?type=1&s=%s&limit=%s'%(text.get(),itemCount)
 
 #get请求
 header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36'}
 html = requests.get(url,header)
 data = json.loads(html.text)
 m_List = []

 try:
 listBox.delete(0,listBox.size())
 for MusicData in data['result']['songs']:
  listBox.insert(END,MusicData['name'] +'------'+'(' +MusicData['artists'][0]['name'] + ')')
  m_List.append(MusicData['audio'])
 except Exception as e: 
 tkMessageBox.showinfo('温馨提示','查询过程出现错误,请重试')
 #print '查询过程出现错误,请重试'
 
 
def play(args):
 try:
 global mp3
 sy = listBox.curselection()[0]
 mp3 = mp3play.load(m_List[int(sy)])
 mp3.play()
 #time.sleep(1000)
 except Exception as e:
 pass

 
def main():
 createWnd()


if __name__ == '__main__':
 main()

程序运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用python实现unix2dos和dos2unix命令的例子

由于工作电脑网络限制无法安装unix2dos和dos2unix命令转换文件,自己实现一个 直接上代码,保存为python文件如unix2dos.py然后使用命令 unix2dos.p...

Pytorch 实现sobel算子的卷积操作详解

Pytorch 实现sobel算子的卷积操作详解

卷积在pytorch中有两种实现,一种是torch.nn.Conv2d(),一种是torch.nn.functional.conv2d(),这两种方式本质都是执行卷积操作,对输入的要求也...

Python中unittest模块做UT(单元测试)使用实例

待测试的类(Widget.py) # Widget.py # Python 2.7.6 class Widget: def __init__(self, size =...

Python使用CMD模块更优雅的运行脚本

本文实例讲述了Python使用CMD模块更优雅的运行脚本的方法。分享给大家供大家参考。具体分析如下: 平时由于经常给测试人员调试一些东西,虽然写了一些脚本,感觉还是不方便。 python...

python在ubuntu中的几种安装方法(小结)

python在ubuntu下有几种安装方法: 通过ubuntu官方的apt工具包安装 通过PPA(Personal Package Archive) 的apt工具包安装 通...