主頁 > 後端開發 > python自制一款炫酷音樂播放器,想聽啥隨便搜!

python自制一款炫酷音樂播放器,想聽啥隨便搜!

2021-07-23 08:11:30 後端開發

前言

晚上坐在電腦面前,想著一邊擼代碼,一邊聽音樂,搜了搜自己想聽的歌,奈何好多歌曲都提示需要著作權,無法播放!

沒辦法,想聽歌還是得靠自己解決!今天就一起用python自制一款炫酷的音樂播放器吧~

首先一起來看看最終實作的音樂播放器效果:
在這里插入圖片描述
下面,我們開始介紹這個音樂播放器的制作程序,

一、核心功能設計

總體來說,我們首先需要設計UI界面,對播放器的畫面布局進行排版設計;其次我們的這款音樂播放器的主要功能包括根據關鍵字搜索自動爬取音樂,獲取音樂串列,能進行音樂播放,

當然還少不了一些附加功能,例如播放方式串列回圈、單曲回圈、隨機播放,當前上一首下一首播放,播放暫停開始,音量增加減少,播放歷史查看等,

拆解需求,大致可以整理出核心功能如下:

  • UI設計排版布局

    • 頭部主要包括關鍵字搜索和音樂來源選擇,以及表單最小化,最大化,關閉功能
    • 中間主體包含左右兩側,左側用來顯示播放音樂封面圖,右側用來進行音樂串列顯示
    • 底部主要來顯示當前播放音樂,播放進度條,音量控制,上一首/下一首,暫停/開始,播放方式等附加功能
  • 關鍵字音樂串列爬蟲

    • 通過輸入的搜索關鍵字和選擇的音樂來源,自動爬取對應的音樂資料
    • 將爬取獲取的音樂名進行串列顯示,顯示在中間主體搜索頁
  • 音樂播放

    • 音樂串列中我們需要雙擊某一首歌,對爬取的歌曲封面圖和歌曲進行下載
    • 下載成功,對音樂檔案根據播放進度條進行播放
  • 附加功能

    • 播放音樂時,我們還需要有播放暫停和啟動功能
    • 音量控制提高或者降低
    • 當前播放歌曲上一首、下一首
    • 音樂串列播放方式,串列回圈、單曲回圈、隨機播放

二、實作步驟

1. UI設計排版布局

基于功能點,我們首先考慮進行簡單的UI布局設計,這里我們使用的是pyqt5,核心設計代碼如下:

def init_ui(self):
    global type
    self.setFixedSize(1025, 750)
    self.main_widget = QWidget()  # 創建視窗主部件
    self.main_layout = QGridLayout()  # 創建主部件的網格布局
    self.main_widget.setLayout(self.main_layout)  # 設定視窗主部件布局為網格布局

    self.close_widget = QWidget()  # 創建關閉側部件
    self.close_widget.setObjectName('close_widget')
    self.close_layout = QGridLayout()  # 創建左側部件的網格布局層
    self.close_widget.setLayout(self.close_layout)  # 設定左側部件布局為網格

    self.left_widget = QWidget()  # 創建左邊側部件
    self.left_widget.setObjectName('left_widget')
    self.left_layout = QGridLayout()  # 創建左側部件的網格布局層
    self.left_widget.setLayout(self.left_layout)  # 設定左側部件布局為網格

    self.right_widget = QWidget()  # 創建右側部件
    self.right_widget.setObjectName('right_widget')
    self.right_layout = QGridLayout()
    self.right_widget.setLayout(self.right_layout)  # 設定右側部件布局為網格

    self.down_widget = QWidget()  # 創建下面部件
    self.down_widget.setObjectName('down_widget')
    self.down_layout = QGridLayout()
    self.down_widget.setLayout(self.down_layout)  # 設定下側部件布局為網格

    self.up_widget = QWidget()  # 創建下面部件
    self.up_widget.setObjectName('up_widget')
    self.up_layout = QGridLayout()
    self.up_widget.setLayout(self.up_layout)  # 設定下側部件布局為網格

    self.label = QLabel(self)
    self.label.setText("還沒有播放歌曲呢╰(*°▽°*)╯")
    self.label.setStyleSheet("color:white")
    self.label.setMaximumSize(310, 20)

    self.main_layout.addWidget(self.up_widget, 0, 0, 1, 115)

    self.main_layout.addWidget(self.left_widget, 1, 0, 90, 25)
    self.main_layout.addWidget(self.right_widget, 1, 25, 90, 90)  # 22右側部件在第0行第3列,占8行9列
    self.main_layout.addWidget(self.down_widget, 100, 0, 10, 115)
    self.main_layout.addWidget(self.close_widget, 0, 110, 1, 5)  # 左側部件在第0行第0列,占1行3列

    self.down_layout.addWidget(self.label, 1, 0, 1, 1)
    self.setCentralWidget(self.main_widget)  # 設定視窗主部件

    self.tabWidget = QTabWidget(self)
    self.tabWidget.setGeometry(QRect(33, 20, 716, 471))
    self.tab = QWidget()
    self.tab.setObjectName("tab")
    self.tab_layout = QGridLayout()
    self.tab.setLayout(self.tab_layout)
    self.listwidget = QListWidget(self.tab)
    self.listwidget.doubleClicked.connect(lambda: self.change_func(self.listwidget))
    self.listwidget.setContextMenuPolicy(Qt.CustomContextMenu)
    self.listwidget.customContextMenuRequested[QPoint].connect(self.myListWidgetContext)
    self.listwidget.setObjectName("listWidget")
    self.tab_layout.addWidget(self.listwidget, 0, 0, 1, 1)
    self.tabWidget.addTab(self.tab, "      搜索頁      ")

    self.tab2 = QWidget()
    self.tab2.setObjectName("tab")
    self.tab2_layout = QGridLayout()
    self.tab2.setLayout(self.tab2_layout)
    self.listwidget2 = QListWidget(self.tab2)
    self.listwidget2.doubleClicked.connect(lambda: self.change_funcse(self.listwidget2))
    self.listwidget2.setContextMenuPolicy(Qt.CustomContextMenu)
    self.listwidget2.customContextMenuRequested[QPoint].connect(self.myListWidgetContext2)
    self.listwidget2.setObjectName("listWidget2")
    self.listwidget2.setContextMenuPolicy(3)
    self.tab2_layout.addWidget(self.listwidget2, 0, 0, 1, 1)
    self.tabWidget.addTab(self.tab2, "      最近播放      ")

    self.right_layout.addWidget(self.tabWidget, 3, 0, 100, 90)

    self.left_close = QPushButton("")  # 關閉按鈕
    self.left_close.clicked.connect(self.close)
    self.left_visit = QPushButton("")  # 空白按鈕
    self.left_visit.clicked.connect(self.big)
    self.left_mini = QPushButton("")  # 最小化按鈕
    self.left_mini.clicked.connect(self.mini)
    self.close_layout.addWidget(self.left_mini, 0, 0, 1, 1)
    self.close_layout.addWidget(self.left_close, 0, 2, 1, 1)
    self.close_layout.addWidget(self.left_visit, 0, 1, 1, 1)
    self.left_close.setFixedSize(15, 15)  # 設定關閉按鈕的大小
    self.left_visit.setFixedSize(15, 15)  # 設定按鈕大小
    self.left_mini.setFixedSize(15, 15)  # 設定最小化按鈕大小
    self.left_close.setStyleSheet(
        '''QPushButton{background:#F76677;border-radius:5px;}QPushButton:hover{background:red;}''')
    self.left_visit.setStyleSheet(
        '''QPushButton{background:#F7D674;border-radius:5px;}QPushButton:hover{background:yellow;}''')
    self.left_mini.setStyleSheet(
        '''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}''')


    self.button_123 = QLabel("")
    self.left_layout.addWidget(self.button_123, 0, 2, 2, 2)
    self.label2 = QLabel(self)
    self.label2.setText("當前為順序播放")
    self.label2.setStyleSheet("color:green")
    self.left_layout.addWidget(self.label2, 4, 0, 2, 1)
    self.button_1234 = QPushButton(icon('fa.download', color='#3FC89C', font=24), "")
    self.button_1234.clicked.connect(self.down)
    self.button_1234.setStyleSheet(
        '''QPushButton{background:#222225;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')
    self.left_layout.addWidget(self.button_1234, 4, 2, 2, 1)
    self.button_1234 = QPushButton(icon('fa.heart', color='#3FC89C', font=24), "")
    self.button_1234.clicked.connect(self.lovesong)
    self.button_1234.setStyleSheet(
        '''QPushButton{background:#222225;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')
    self.left_layout.addWidget(self.button_1234, 4, 3, 2, 2)
    self.label3 = QLabel(self)
    self.label3.setText("")
    self.label3.setStyleSheet("color:white")
    self.down_layout.addWidget(self.label3, 1, 3, 1, 1)

    self.label7 = QLabel(self)
    self.label7.setText("")
    self.label7.setStyleSheet("color:white")
    self.label5 = QLabel(self)
    pix_img = QPixmap(str(data + '/backdown.png'))
    pix = pix_img.scaled(300, 300, Qt.KeepAspectRatio)
    self.label5.setPixmap(pix)
    # self.label5.setMaximumSize(1,1)
    self.left_layout.addWidget(self.label5, 2, 0, 2, 8)
    self.label6 = QLabel(self)
    self.label6.setText("")
    self.label6.setStyleSheet("color:#6DDF6D")
    self.left_layout.addWidget(self.label6, 2, 0, 2, 2)

    self.label23 = QLabel(self)
    self.label23.setText("                 ")
    self.label23.setStyleSheet("color:#6DDF6D")
    self.up_layout.addWidget(self.label23, 0, 100, 1, 20)

    self.shuru = QLineEdit("")
    self.up_layout.addWidget(self.shuru, 0, 120, 1, 40)
    self.shuru.returnPressed.connect(self.correct)

    self.label23 = QLabel(self)
    self.label23.setText("     軟體")
    self.label23.setStyleSheet("color:#6DDF6D")
    self.up_layout.addWidget(self.label23, 0, 160, 1, 10)

    self.label61 = QLabel(self)
    self.label61.setText("")
    self.label61.setStyleSheet("color:#6DDF6D")
    self.up_layout.addWidget(self.label61, 0, 200, 1, 50)

    self.cb = QComboBox(self)
    self.cb.addItems(['網易云', '酷狗',  'qq'])
    self.up_layout.addWidget(self.cb, 0, 180, 1, 30)
    self.cb.currentIndexChanged[int].connect(self.print)
    self.button_1 = QPushButton(icon('fa.search', color='white'), "")
    self.button_1.clicked.connect(self.correct)
    self.button_1.setStyleSheet(
        '''
        QPushButton{color:white;border-radius:5px;}QPushButton:hover{background:green;}
        ''')
    self.up_layout.addWidget(self.button_1, 0, 155, 1, 5)

    self.right_process_bar = QProgressBar()  # 播放進度部件
    self.right_process_bar.setValue(49)
    self.right_process_bar.setFixedHeight(3)  # 設定進度條高度
    self.right_process_bar.setTextVisible(False)  # 不顯示進度條文字
    self.right_process_bar.setRange(0, 10000)

    self.right_playconsole_widget = QWidget()  # 播放控制部件
    self.right_playconsole_layout = QGridLayout()  # 播放控制部件網格布局層
    self.right_playconsole_widget.setLayout(self.right_playconsole_layout)

    self.console_button_1 = QPushButton(icon('fa.backward', color='#3FC89C'), "")
    self.console_button_1.clicked.connect(self.last)
    self.console_button_1.setStyleSheet(
        '''QPushButton{background:#222225;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')

    self.console_button_2 = QPushButton(icon('fa.forward', color='#3FC89C'), "")
    self.console_button_2.clicked.connect(self.nextion)
    self.console_button_2.setStyleSheet(
        '''QPushButton{background:#222225;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')

    self.console_button_3 = QPushButton(icon('fa.pause', color='#3FC89C', font=18), "")
    self.console_button_3.clicked.connect(self.pause)
    self.console_button_3.setStyleSheet(
        '''QPushButton{background:#222225;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')

    self.console_button_4 = QPushButton(icon('fa.volume-down', color='#3FC89C', font=18), "")
    self.console_button_4.clicked.connect(self.voicedown)
    self.console_button_4.setStyleSheet(
        '''QPushButton{background:#222225;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')

    self.console_button_5 = QPushButton(icon('fa.volume-up', color='#3FC89C', font=18), "")
    self.console_button_5.clicked.connect(self.voiceup)
    self.console_button_5.setStyleSheet(
        '''QPushButton{background:#222225;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')

    self.console_button_6 = QPushButton(icon('fa.align-center', color='#3FC89C', font=18), "")
    self.console_button_6.clicked.connect(self.playmode)
    self.console_button_6.setStyleSheet(
        '''QPushButton{background:#222225;border-radius:5px;}QPushButton:hover{background:#3684C8;}''')

    self.console_button_3.setIconSize(QSize(30, 30))

    self.right_playconsole_layout.addWidget(self.console_button_4, 0, 0)

    self.right_playconsole_layout.addWidget(self.console_button_1, 0, 1)
    self.right_playconsole_layout.addWidget(self.console_button_3, 0, 2)

    self.right_playconsole_layout.addWidget(self.console_button_2, 0, 3)

    self.right_playconsole_layout.addWidget(self.console_button_5, 0, 4)

    self.right_playconsole_layout.addWidget(self.console_button_6, 0, 5)
    self.right_playconsole_layout.setAlignment(Qt.AlignCenter)  # 設定布局內部件居中顯示
    self.down_layout.addWidget(self.right_process_bar, 0, 0, 1, 4)  # 第0行第0列,占8行3列
    # 第0行第0列,占8行3列
    self.down_layout.addWidget(self.label7, 1, 2, 1, 1)
    self.down_layout.addWidget(self.right_playconsole_widget, 1, 0, 1, 4)
    self.setWindowOpacity(0.95)  # 設定視窗透明度
    self.setAttribute(Qt.WA_TranslucentBackground)
    self.setWindowFlag(Qt.FramelessWindowHint)  # 隱藏邊框
    self.main_layout.setSpacing(0)

實作效果如下:
在這里插入圖片描述

2. 關鍵字音樂串列爬蟲

我們可以根據輸入的關鍵字和音樂來源進行音樂爬取,這里我們需要通過多執行緒,將歌曲、歌手、歌曲url地址全都獲取,核心代碼如下:

def run(self):
  qmut.lock()
  try:
      global paing
      global stop
      global lrcs
      global urls
      global songs
      global name
      global songid
      global proxies
      global pic
      global tryed
      paing = True

      print('搜索軟體{}'.format(type))
      print('開始搜索')
      name = name
      headers = {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.110.430.128 Safari/537.36',
          'X-Requested-With': 'XMLHttpRequest'

      }
      urls = []
      songs = []
      pic = []
      lrcs = []
      pages = 5
      print(pages)
      for a in range(0, pages):
          if not stop:

              urlss = ['http://music.9q4.cn/', 'https://defcon.cn/dmusic/','http://www.xmsj.org/',
                      'http://music.laomao.me/']
              print (tryed)
              if tryed >3:

                  tryed = 0
                  url = urlss[tryed]
              else:
                  url = urlss[tryed]
              print (urlss[tryed])

              params = {'input': name,
                        'filter': 'name',
                        'type': type,
                        'page': a
                        }
              if not stop:
                  try:
                      res = post(url, params, headers=headers, proxies=proxies)
                      html = res.json()

                      for i in range(0, 10):

                              try:
                                  title = jsonpath(html, '$..title')[i]
                                  author = jsonpath(html, '$..author')[i]
                                  url1 = jsonpath(html, '$..url')[i]  # 取下載網址
                                  pick = jsonpath(html, '$..pic')[i]  # 取歌詞
                                  lrc = jsonpath(html, '$..lrc')[i]
                                  print(title, author)
                                  lrcs.append(lrc)
                                  urls.append(url1)
                                  pic.append(pick)
                                  songs.append(str(title) + ' - ' + str(author))
                              except:
                                  pass
                  except:
                      stop = False
                      paing = False
                  self.trigger.emit(str('finish'))
              else:
                  self.trigger.emit(str('finish'))
          else:
              self.trigger.emit(str('clear'))
              pass

      stop = False
      paing = False
  except:
      print('爬取歌曲出錯')
      self.trigger.emit(str('unfinish'))
      stop = False
      paing = False
  qmut.unlock()

爬取代碼寫好了,我們還需要將爬取的這些音樂資料串列顯示到畫面中搜索頁面中,代碼如下:

def repite(self, name, type):
    global tryed
    global paing
    global stop
    self.listwidget.clear()
    self.listwidget.addItem('搜索中')
    self.listwidget.item(0).setForeground(Qt.white)
    try:
        if paing:
            stop = True

            self.listwidget.clear()
            self.work2 = PAThread()
            self.work2.start()
            self.work2.trigger.connect(self.seafinish)
        else:
            self.work2 = PAThread()
            self.work2.start()
            self.work2.trigger.connect(self.seafinish)
    except:
        tryed = tryed + 1
        get_info('https://www.kuaidaili.com/free/inha')
        self.listwidget.addItem('貌似沒網了呀`(*>﹏<*)′,再試一遍吧~')
        self.listwidget.item(0).setForeground(Qt.white)

效果如下:
在這里插入圖片描述

3. 音樂播放

關鍵字搜索音樂串列完成之后,接下來我們需要實作音樂播放功能,首先需要從爬取的url下載待播放的歌曲,這里還是通過多執行緒進行,核心代碼如下:

class WorkThread(QThread):
    trigger = pyqtSignal(str)

    def __int__(self):
        # 初始化函式
        super(WorkThread, self).__init__()
    
    # 進度條
    def cbk(self, a, b, c):
        '''''回呼函式
        @a:已經下載的資料塊
        @b:資料塊的大小
        @c:遠程檔案的大小
        '''
        per = 100.0 * a * b / c
        if per > 100:
            per = 100
        # print   ('%.2f%%' % per)
        self.trigger.emit(str('%.2f%%' % per))

    def run(self):
        try:
            global number
            global path
            global downloading
                        try:
                proxies = {
                    'http': 'http://124.72.109.183:8118',
                    ' Shttp': 'http://49.85.1.79:31666'

                }
                headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
                    'X-Requested-With': 'XMLHttpRequest'}
                try:
                    try:
                        try:
                            aq = pic[num]
                            aqq = aq.split('/')

                        except:
                            pass

                        if type == 'kugou' and len(aqq) - 1 == 6:
                            aqqe = str(aqq[0]) + str('//') + str(aqq[2]) + str('/') + str(aqq[3]) + str('/') + str(
                                '400') + str('/') + str(aqq[5]) + str('/') + str(aqq[6])
                            print(aqqe)
                        elif type == 'netease' and len(aqq) - 1 == 4:
                            aqn = aq.split('?')
                            b = '?param=500x500'
                            aqqe = (str(aqn[0]) + str(b))
                            print(aqqe)
                        else:
                            aqqe = pic[num]
                        req = get(aqqe)

                        checkfile = open(str(data + '/ls1.png'), 'w+b')
                        for i in req.iter_content(100000):
                            checkfile.write(i)

                        checkfile.close()
                        lsfile = str(data + '/ls1.png')
                        safile = str(data + '/back.png')
                        draw(lsfile, safile)
                    except:
                        pass
                    url1 = urls[num]
                    print(url1)
                    number = number + 1
                    path = str(data + '\{}.臨時檔案'.format(number))
                    headers = {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.110.430.128 Safari/537.36',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                    with get(url1, stream=True, headers=headers) as r, open(path, 'wb') as file:
                        total_size = int(r.headers['content-length'])
                        content_size = 0
                        for content in r.iter_content(chunk_size=1024):
                            file.write(content)
                            content_size += len(content)
                            plan = (content_size / total_size) * 100
                            # print(int(plan))
                            develop = str(int(plan)) + str('%')
                            self.trigger.emit(str(develop))
                    to = 'downloadmusic\{}.mp3'.format(songs[num])
                    makedirs('downloadmusic', exist_ok=True)
                except:
                    pass
                try:
                    copyfile(path, to)
                except:
                    pass
                downloading = False
                self.trigger.emit(str('finish'))
            except:
                self.trigger.emit(str('nofinish'))

音樂播放模塊:

    def bofang(self, num, bo):
        print('嘗試進行播放')
        try:
            import urllib
            global pause
            global songs
            global music
            global downloading
            downloading = True
            self.console_button_3.setIcon(icon('fa.pause', color='#F76677', font=18))
            pause = False
            try:
                mixer.stop()
            except:
                pass
            mixer.init()
            try:
                self.Timer = QTimer()
                self.Timer.start(500)
            except:
                pass
            try:
                self.label.setText('正在尋找檔案...')
                self.work = WorkThread()
                self.work.start()
                self.work.trigger.connect(self.display)
            except:
                print('無法播放,歌曲下載錯誤')
                downloading = False
                pass
        except:
            sleep(0.1)
            print('播放系統錯誤')
            # self.next()
            pass

    def display(self, sd):
        global pause
        global songed
        global urled
        global lrcd
        global timenum
        if sd == 'finish':
            try:
                if bo == 'boing':
                    self.label.setText(songs[num])
                elif bo == 'boed':
                    self.label.setText(songed[num])
                elif bo == 'love':
                    self.label.setText(loves[num])
                try:
                    pix_img = QPixmap(str(data + '/back.png'))
                    pix = pix_img.scaled(300, 300, Qt.KeepAspectRatio)
                    self.label5.setPixmap(pix)
                except:
                    pix_img = QPixmap(str(data + '/backdown.png'))
                    pix = pix_img.scaled(300, 300, Qt.KeepAspectRatio)
                    self.label5.setPixmap(pix)
                print(str(data + '\{}.臨時檔案'.format(number)))
                mixer.music.load(str(data + '\{}.臨時檔案'.format(number)))  # 載入音樂
                mixer.music.play()
                self.console_button_3.setIcon(icon('fa.pause', color='#F76677', font=18))
                pause = False
                try:
                    mp3 = str(data + '\{}.臨時檔案'.format(number))
                    xx = load(mp3)
                    timenum = xx.info.time_secs
                    global start
                    start = True
                except:
                    print('MP3錯誤,播放失敗')

                if bo == 'boing':
                    songed.append(songs[num])
                    urled.append(urls[num])
                    picd.append(pic[num])
                    lrcd.append(lrcs[num])
                    r = 0
                    self.listwidget2.clear()
                    for i in songed:
                        # self.listwidget.addItem(i)#將檔案名添加到listWidget

                        self.listwidget2.addItem(i)
                        self.listwidget2.item(r).setForeground(Qt.white)
                        r = r + 1
                else:
                    pass
                # 播放音樂
            except:
                pass
        elif sd == 'nofinish':
            self.label.setText('下載錯誤')
        elif sd == 'lrcfinish':
            r = 0
            for i in lrct:
                if not i == '\r':
                    r = r + 1
                else:
                    pass
        elif sd == 'lrcnofinish':
            pass
        else:
            self.label.setText('加速下載中,已完成{}'.format(sd))

至此,我們的音樂播放器已經可以正常播放音樂了,
在這里插入圖片描述

4. 附加功能

主要功能已經完成了,下面我們還可以添加一些附加功能,例如播放方式串列回圈、單曲回圈、隨機播放,當前上一首下一首播放,播放暫停開始,音量增加減少等等,

播放模式:

(1)隨機播放:

def shui(self):
    global num
    global songs
    if bo == 'boing':
        q = int(len(songs) - 1)
        num = int(randint(1, q))
    elif bo == 'love':
        q = int(len(loves) - 1)
        num = int(randint(1, q))
    else:
        q = int(len(songed) - 1)
        num = int(randint(0, q))

    try:
        print('隨機播放下一首')
        mixer.init()
        self.Timer = QTimer()
        self.Timer.start(500)
        # self.Timer.timeout.connect(self.timercontorl)#時間函式,與下面的進度條和時間顯示有關
        if bo == 'boing':
            self.label.setText(songs[num])
        elif bo == 'love':
            self.label.setText(loves[num])
        else:
            self.label.setText(songed[num])
        self.bofang(num, bo)  # 播放音樂
    except:
        pass

(2) 上一首、下一首:

def last(self):
    global num
    global songs
    if num == 0:
        print('冇')
        num = len(songs) - 1
    else:
        num = num - 1
    try:
        self.bofang(num)
        self.label.setText(songs[num])
    except:
        pass

#下一首
def next(self):
    print ('nexting')
    global num
    global songs
    if num == len(songs) - 1:
        print('冇')
        num = 0
    else:
        num = num + 1
    try:
        self.label.setText(songs[num])
        self.bofang(num)
    except:
        print ('next error')
        pass

(3)單曲回圈:

def always(self):
    try:
        if bo == 'boing':
            self.label.setText(songs[num])
        else:
            self.label.setText(songed[num])
        self.bofang(num, bo)  # 播放音樂

    except:
        pass

(4) 播放模式選擇:

def playmode(self):
    global play
    try:
        if play == 'shun':
            play = 'shui'
            print('切換到隨機播放')
            self.label2.setText("當前為隨機播放")
            try:
                self.console_button_6.setIcon(icon('fa.random', color='#3FC89C', font=18))
                print('done')
            except:
                print('none')
                pass
            # self.left_shui.setText('切換為單曲回圈')
        elif play == 'shui':
            play = 'always'
            print('切換到單曲回圈')
            self.label2.setText("當前為單曲回圈")
            try:
                self.console_button_6.setIcon(icon('fa.retweet', color='#3FC89C', font=18))
                print('done')
            except:
                print('none')

            # self.left_shui.setText('切換為順序播放')
        elif play == 'always':
            play = 'shun'
            print('切換到順序播放')
            self.label2.setText("當前為順序播放")
            try:
                self.console_button_6.setIcon(icon('fa.align-center', color='#3FC89C', font=18))
                print('done')
            except:
                print('none')

            # self.left_shui.setText('切換為隨機播放')
    except:
        print('模式選擇錯誤')
        pass

播放暫停/開始:

def pause(self):
    global pause
    if pause:
        try:
            mixer.music.unpause()
        except:
            pass
        self.console_button_3.setIcon(icon('fa.pause', color='#3FC89C', font=18))
        pause = False
    else:
        try:
            mixer.music.pause()
        except:
            pass
        self.console_button_3.setIcon(icon('fa.play', color='#F76677', font=18))
        pause = True

音量提高/降低:

def voiceup(self):
    try:
        print('音量加大')
        global voice
        voice += 0.1
        if voice > 1:
            voice = 1
        mixer.music.set_volume(voice)
        k = Decimal(voice).quantize(Decimal('0.00'))
        self.label3.setText('音量:{}'.format(str(k * 100) + '%'))
    except:
        pass

def voicedown(self):
    try:
        print('音量減少')
        global voice
        voice -= 0.1
        if voice < 0:
            voice = 0
        mixer.music.set_volume(voice)
        k = Decimal(voice).quantize(Decimal('0.00'))
        self.label3.setText('音量:{}'.format(str(k * 100) + '%'))
    except:
        pass

至此,這款音樂播放器就基本完成啦~ 一起來看看效果吧!

<iframe id="OIqnJ20S-1626741281570" src="https://live.csdn.net/v/embed/171282" allowfullscreen="true" data-mediaembed="csdn"></iframe>

三、結束語

當然這款音樂播放器還有待完善的功能尚未完成:

  • 音樂本地下載保存
  • 播放本地音樂
  • 添加我喜愛的音樂功能
  • 歌詞播放
  • 音樂進度跳播

后面有時間這些功能也會繼續完善下!今天我們就到這里,明天繼續努力!
在這里插入圖片描述
若本篇內容對您有所幫助,請三連點贊,關注,收藏支持下,

創作不易,白嫖不好,各位的支持和認可,就是我創作的最大動力,我們下篇文章見!

Dragon少年 | 文

如果本篇博客有任何錯誤,請批評指教,不勝感激 !

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/289602.html

標籤:python

上一篇:你的python挑戰吳亦凡rap,渣男實錘

下一篇:【Python從入門到精通】(十二)Python函式的高級知識點,更深入的吸收知識,不做知識的牙簽(不淺嘗輒止)【收藏下來保證有用!!!】

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more