您的位置:首頁技術文章
文章詳情頁

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

瀏覽:3日期:2022-07-27 14:09:42

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

1.網易云非付費內容爬取器(聲明:由于技術十分簡單,未到觸犯軟件使用規則的程度)驅動Edge瀏覽器(自己寫驅動會更高端)進入界面,爬取列表中第一個音頻地址并存入相應文件夾中。這里有一個最簡單的爬蟲程序和一個最簡單的tkinter GUI編程。

注意,要先在網易云音樂網頁中將第一個對應音頻鏈接的位置定位:

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

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

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 webdriverglobal entryimport osfrom 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:pythonmsedgedriver’) 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 = ’開始下載’,font = (’楷書’,15),command=get_music_name)button.grid(row=2, column=0,sticky=W)button1 = Button(root,text = ’退出程序’,font = (’楷書’,15),command=root.quit)button1.grid(row=2, column=1,sticky=E)#顯示當前的界面內容root.mainloop()

運行效果

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

發現music_netease文件夾中相關文件赫然在列。

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

簡易音樂播放器:這個控件在界面上仍然使用Tkinter,只不過沒有通過編程,而是利用pygame庫中的音頻模塊,在邏輯上增加了上一曲、下一曲(讀取上一個文件、下一個文件)、音量控制、簡單的線程控制等。

import osimport tkinterimport tkinter.filedialogimport timeimport threadingimport pygame#第一步 搭建界面root = tkinter.Tk()root.title(’音樂播放器’)#窗口大小和位置root.geometry(’460x600+500+100’)#不能拉伸root.resizable(False,False)folder = ’’#文件路徑res = []num = 0now_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,y=10,width=50,height=20)buttonPlay[’state’] = ’disabled’#停止播放buttonStop = tkinter.Button(root,text = ’停止’,command=bottonStopClik)#布局buttonStop.place(x=120,y=10,width=50,height=20)#狀態buttonStop[’state’] = ’disabled’# 下一首buttonNext = tkinter.Button(root,text=’下一首’,command =bottonNextClik)buttonNext.place(x=260,y=10,width=50,height=20)buttonNext[’state’] = ’disabled’#上一首buttonPrev = tkinter.Button(root,text=’上一首’,command =bottonPrevClik)buttonPrev.place(x = 330,y=10,width=50,height=20)buttonPrev[’state’] = ’disabled’musicName = tkinter.StringVar(root,value=’暫時沒有播放音樂’)labelName = tkinter.Label(root,textvariable=musicName)labelName.place(x=10,y=30,width=260,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實現音樂播放和下載小程序功能的文章就介紹到這了,更多相關python--音樂播放和下載小程序內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区