1. 程式人生 > 程式設計 >python實現音樂播放和下載小程式功能

python實現音樂播放和下載小程式功能

(本篇部分程式碼綜合整理自B站,B站有手把手說明的教程)

1.網易雲非付費內容爬取器(宣告:由於技術十分簡單,未到觸犯軟體使用規則的程度)驅動Edge瀏覽器(自己寫驅動會更高階)進入介面,爬取列表中第一個音訊地址並存入相應資料夾中。這裡有一個最簡單的爬蟲程式和一個最簡單的tkinter GUI程式設計。

注意,要先在網易雲音樂網頁中將第一個對應音訊連結的位置定位:

在這裡插入圖片描述

對於以上定位可通過如下方式獲得(定位器):

 req = driver.find_element_by_id('m-search')
 a_id = req.find_element_by_xpath('.//div[@class = "item f-cb h-flag "]/div[2]//a').get_attribute("href")

在XML語言中尋找連結路徑的方法可參見find_element_by_xpath
建立目錄參見makedirs

這裡的GUI需要tkinter新增文字。用text控制元件insert(插入文字)、see(滾動)、update(更新)等方法顯示正在下載和已下載圖樣;在get_music_name函式中,首先從輸入視窗獲取名稱,然後呼叫Edge驅動訪問網易雲音樂主頁,通過'http://music.163.com/song/media/outer/url?id={}.mp3'.format(song_id)搜到歌曲,通過上述定位器找到歌曲地址和歌名。注意到第一個函式傳入的應該是字典型別(有了這種語句:song_id = item['song_id']

),那就建立一個字典後在函式體內呼叫song_load實現下載。在這之前,驅動就完成了任務,所以可以關閉驅動。
至於Tkinter的控制元件內容,應該根據實際情況試錯和設計,介面程式設計相對還是比較簡單的。(分別建立標籤控制元件、輸入框、列表框、按鈕,並依次確定它們在主介面中的位置)

from tkinter import *
from selenium import webdriver
global entry
import os
from urllib.request import urlretrieve
#2.下載歌曲
def song_load(item):


 song_id = item['song_id']
 song_name = item['song_name']

 song_url = 'http://music.163.com/song/media/outer/url?id={}.mp3'.format(song_id)

 #建立資料夾
 os.makedirs('music_netease',exist_ok=True)
 path = 'music_netease\{}.mp3'.format(song_name)

 #顯示資料到文字框
 text.insert(END,'歌曲:{},正在下載...'.format(song_name))
 #文字框滾動
 text.see(END)
 #更新
 text.update()
 #下載
 urlretrieve(song_url,path)
 #顯示資料到文字框
 text.insert(END,'歌曲:{},下載完畢'.format(song_name))
 #文字框滾動
 text.see(END)
 #更新
 text.update()
#1.搜尋
def get_music_name():
 #獲取輸入的內容
 name = entry.get()

 url = 'https://music.163.com/#/search/m/?s={}&type=1'.format(name)
 #搜尋頁面

 option = webdriver.EdgeOptions()
 option.add_argument('--headless')
 #driver = webdriver.Edge(edge_options=option)

 driver = webdriver.Edge('D:\\python\\msedgedriver')

 driver.get(url)
 driver.switch_to.frame('g_iframe')
 #獲取歌曲的id
 req = driver.find_element_by_id('m-search')
 a_id = req.find_element_by_xpath('.//div[@class = "item f-cb h-flag "]/div[2]//a').get_attribute("href")

 song_id = a_id.split('=')[-1]
 print(song_id)

 song_name = req.find_element_by_xpath('.//div[@class="item f-cb h-flag "]/div[2]//b').get_attribute("title")
 print(song_name)
 #構造字典
 item = {}
 item['song_id'] = song_id
 item['song_name'] = song_name
 driver.quit()
 #下載歌曲
 song_load(item)

#get_music_name()


#形象工程
# 搭建介面
#建立畫板
root = Tk()

#標題
root.title('網易雲下載器')
#設定視窗大小
root.geometry('560x450+400+200')
#標籤控制元件
label = Label(root,text = '輸入要下載的歌曲:',font = ('華文行楷',20))
#標籤定位
label.grid()
#輸入框
entry = Entry(root,font = ('楷書',20))
#定位
entry.grid(row = 0,column = 1)
#列表框
text = Listbox(root,font = ('隸書',16),width = 50,heigh = 15)
text.grid(row = 1,columnspan = 2)
#點選按鈕
button = Button(root,text = '開始下載',15),command=get_music_name)
button.grid(row=2,column=0,sticky=W)

button1 = Button(root,text = '退出程式',command=root.quit)
button1.grid(row=2,column=1,sticky=E)
#顯示當前的介面內容
root.mainloop()

執行效果

在這裡插入圖片描述

發現music_netease資料夾中相關檔案赫然在列。

在這裡插入圖片描述

簡易音樂播放器:
這個控制元件在介面上仍然使用Tkinter,只不過沒有通過程式設計,而是利用pygame庫中的音訊模組,在邏輯上增加了上一曲、下一曲(讀取上一個檔案、下一個檔案)、音量控制、簡單的執行緒控制等。

import os
import tkinter
import tkinter.filedialog
import time
import threading
import pygame

#第一步 搭建介面
root = tkinter.Tk()
root.title('音樂播放器')
#視窗大小和位置
root.geometry('460x600+500+100')
#不能拉伸
root.resizable(False,False)

folder = ''#檔案路徑
res = []
num = 0
now_music = ''
#第二步 功能實現
def buttonChooseClik():
 '''新增檔案函式'''
 global folder
 global res
 if not folder:
  folder = tkinter.filedialog.askdirectory()#選擇目錄
  musics = [folder + '\\' + music
     for music in os.listdir(folder) if music.endswith(('.mp3','ogg'))]
  ret = []
  for i in musics:
   ret.append(i.split('\\')[1:])
   res.append(i.replace('\\','/'))
  var2 = tkinter.StringVar()
  var2.set(ret)
  #放入列表框
  lb = tkinter.Listbox(root,listvariable =var2)
  lb.place(x=50,y=100,width=260,height=300)
 if not folder:
  return
 global playing
 playing = True

 # 根據情況禁用和啟用相應的按鈕
 buttonPlay['state'] = 'normal'
 buttonStop['state'] = 'normal'
 pause_resume.set('播放')


def play():
 '''播放音樂的函式'''
 #初始化混音器裝置
 if len(res):
  pygame.mixer.init()
  global num
  while playing:
   if not pygame.mixer.music.get_busy():
    #隨機播放一首歌曲
    nextMusic =res[num]
    print(nextMusic)
    print(num)
    pygame.mixer.music.load(nextMusic.encode())
    #播放一次
    pygame.mixer.music.play(1)
    #print(len(res)-1)
    if len(res) -1==num:
     num=0
    else:
     num = num+1
    nextMusic = nextMusic.split('\\')[1:]
    musicName.set('playing....'+''.join(nextMusic))
   else:
    time.sleep(0.1)

def bottonPlayClik():
 '''點選播放'''
 buttonNext['state'] = 'normal'
 buttonPrev['state'] = 'normal'

 if pause_resume.get() == '播放':
  pause_resume.set('暫停')
  global folder
  if not folder:
   #選擇目錄,返回目錄名
   folder = tkinter.filedialog.askdirectory()
  if not folder:
   return
  global playing
  playing = True

  #建立執行緒,主執行緒接受使用者操作

  t = threading.Thread(target=play)
  t.start()
 elif pause_resume.get() == '暫停':
  pygame.mixer.music.pause()
  pause_resume.set('繼續')
 elif pause_resume.get() == '繼續':
  pygame.mixer.music.unpause()
  pause_resume.set('暫停')


def bottonStopClik():
 '''停止播放'''
 global playing
 playing = False
 pygame.mixer.music.stop()
def bottonNextClik():
 '''播放下一首'''
 global playing
 playing = False
 pygame.mixer.music.stop()
 global num
 if len(res)== num:
  num = 0
 playing = True

 t = threading.Thread(target=play)
 t.start()

def bottonPrevClik():
 '''播放上一首'''
 global playing
 playing = True
 pygame.mixer.music.stop()
 global num
 if num == 0:
  num = len(res)-2
 elif num == len(res) - 1:
  num -= 2
 else:
  num -=2
 print(num)

 playing = True

 t = threading.Thread(target = play)

 t.start()

def closeWindow():
 '''關閉視窗'''
 global playing
 playing = False
 time.sleep(0.3)
 try:
  pygame.mixer.music.stop()
  pygame.mixer.quit()
 except:
  pass
 root.destroy()

def control_voice(value = 0.5):
 pygame.mixer.music.set_volume(float(value))

#關閉視窗
root.protocol('WM_DELETE_WINDOW',closeWindow)
#新增按鈕
buttonChoose = tkinter.Button(root,text='新增',command=buttonChooseClik)
#佈局
buttonChoose.place(x=50,y=10,width=50,height=20)
#播放按鈕 跟蹤變數值的變化
pause_resume = tkinter.StringVar(root,value='播放')
buttonPlay= tkinter.Button(root,textvariable=pause_resume,command=bottonPlayClik)
buttonPlay.place(x=190,height=20)
buttonPlay['state'] = 'disabled'
#停止播放
buttonStop = tkinter.Button(root,text = '停止',command=bottonStopClik)
#佈局
buttonStop.place(x=120,height=20)
#狀態
buttonStop['state'] = 'disabled'
# 下一首
buttonNext = tkinter.Button(root,text='下一首',command =bottonNextClik)

buttonNext.place(x=260,height=20)

buttonNext['state'] = 'disabled'

#上一首
buttonPrev = tkinter.Button(root,text='上一首',command =bottonPrevClik)
buttonPrev.place(x = 330,height=20)
buttonPrev['state'] = 'disabled'

musicName = tkinter.StringVar(root,value='暫時沒有播放音樂')
labelName = tkinter.Label(root,textvariable=musicName)

labelName.place(x=10,y=30,height=20)

#新增控制元件
s = tkinter.Scale(root,label='音量',from_=0,to=1,orient=tkinter.HORIZONTAL,length=240,showvalue=0,tickinterval=2,resolution=0.1,command=control_voice)

s.place(x=50,y=50,width=200)

#啟動訊息迴圈
root.mainloop()

執行效果:

在這裡插入圖片描述

到此這篇關於python實現音樂播放和下載小程式功能的文章就介紹到這了,更多相關python--音樂播放和下載小程式內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!