<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Python制作一款簡易音樂播放器

          共 6947字,需瀏覽 14分鐘

           ·

          2021-05-11 07:30



          大家好,歡迎來到 Crossin的編程教室 !
          今天給大家分享一個(gè)迷你項(xiàng)目案例:利用Python制作一款簡易音樂播放器。這個(gè)程序具有一定的實(shí)用性,用到的技術(shù)也不算復(fù)雜,可以作為完成基礎(chǔ)學(xué)習(xí)后的練手項(xiàng)目。
          讓我們愉快地開始吧~
          環(huán)境搭建

          安裝Python并添加到環(huán)境變量,pip安裝相關(guān)模塊:

          pip install pyqt5

          先睹為快

          在cmd窗口運(yùn)行"MusicPlayer.py"文件即可。

          效果如下:

          原理簡介

          一、設(shè)計(jì)界面

          界面設(shè)計(jì)的比較簡約,大概長這個(gè)樣子:



          源代碼里一個(gè)個(gè)地定義界面包含的元素,然后排版一下就行了:
          # 界面元素# --播放時(shí)間self.label1 = QLabel('00:00')self.label1.setStyle(QStyleFactory.create('Fusion'))self.label2 = QLabel('00:00')self.label2.setStyle(QStyleFactory.create('Fusion'))# --滑動(dòng)條self.slider = QSlider(Qt.Horizontal, self)self.slider.sliderMoved[int].connect(lambda: self.player.setPosition(self.slider.value()))self.slider.setStyle(QStyleFactory.create('Fusion'))# --播放按鈕self.play_button = QPushButton('播放', self)self.play_button.clicked.connect(self.playMusic)self.play_button.setStyle(QStyleFactory.create('Fusion'))# --上一首按鈕self.preview_button = QPushButton('上一首', self)self.preview_button.clicked.connect(self.previewMusic)self.preview_button.setStyle(QStyleFactory.create('Fusion'))# --下一首按鈕self.next_button = QPushButton('下一首', self)self.next_button.clicked.connect(self.nextMusic)self.next_button.setStyle(QStyleFactory.create('Fusion'))# --打開文件夾按鈕self.open_button = QPushButton('打開文件夾', self)self.open_button.setStyle(QStyleFactory.create('Fusion'))self.open_button.clicked.connect(self.openDir)# --顯示音樂列表self.qlist = QListWidget()self.qlist.itemDoubleClicked.connect(self.doubleClicked)self.qlist.setStyle(QStyleFactory.create('windows'))# --如果有初始化setting, 導(dǎo)入settingself.loadSetting()# --播放模式self.cmb = QComboBox()self.cmb.setStyle(QStyleFactory.create('Fusion'))self.cmb.addItem('順序播放')self.cmb.addItem('單曲循環(huán)')self.cmb.addItem('隨機(jī)播放')# --計(jì)時(shí)器self.timer = QTimer(self)self.timer.start(1000)self.timer.timeout.connect(self.playByMode)# 界面布局self.grid = QGridLayout()self.setLayout(self.grid)self.grid.addWidget(self.qlist, 0, 0, 5, 10)self.grid.addWidget(self.label1, 0, 11, 1, 1)self.grid.addWidget(self.slider, 0, 12, 1, 1)self.grid.addWidget(self.label2, 0, 13, 1, 1)self.grid.addWidget(self.play_button, 0, 14, 1, 1)self.grid.addWidget(self.next_button, 1, 11, 1, 2)self.grid.addWidget(self.preview_button, 2, 11, 1, 2)self.grid.addWidget(self.cmb, 3, 11, 1, 2)self.grid.addWidget(self.open_button, 4, 11, 1, 2)
          二、實(shí)現(xiàn)各部分功能

          (1)存放音樂的文件夾選取

          直接調(diào)pyqt5相應(yīng)的函數(shù)就行:

          '''打開文件夾'''def openDir(self):        self.cur_path = QFileDialog.getExistingDirectory(self, "選取文件夾", self.cur_path)        if self.cur_path:                self.showMusicList()                self.cur_playing_song = ''                self.setCurPlaying()                self.label1.setText('00:00')                self.label2.setText('00:00')                self.slider.setSliderPosition(0)                self.is_pause = True                self.play_button.setText('播放')

          打開文件夾后把所有的音樂文件顯示在界面左側(cè),并保存一些必要的信息:

          '''顯示文件夾中所有音樂'''def showMusicList(self):        self.qlist.clear()        self.updateSetting()        for song in os.listdir(self.cur_path):                if song.split('.')[-1] in self.song_formats:                        self.songs_list.append([song, os.path.join(self.cur_path, song).replace('\\', '/')])                        self.qlist.addItem(song)        self.qlist.setCurrentRow(0)        if self.songs_list:                self.cur_playing_song = self.songs_list[self.qlist.currentRow()][-1]

          (2)音樂播放

          音樂播放功能直接調(diào)用QMediaPlayer實(shí)現(xiàn):

          '''播放音樂'''def playMusic(self):        if self.qlist.count() == 0:                self.Tips('當(dāng)前路徑內(nèi)無可播放的音樂文件')                return        if not self.player.isAudioAvailable():                self.setCurPlaying()        if self.is_pause or self.is_switching:                self.player.play()                self.is_pause = False                self.play_button.setText('暫停')        elif (not self.is_pause) and (not self.is_switching):                self.player.pause()                self.is_pause = True                self.play_button.setText('播放')

          (3)音樂切換

          點(diǎn)擊上一首/下一首按鈕切換:

          '''上一首'''def previewMusic(self):        self.slider.setValue(0)        if self.qlist.count() == 0:                self.Tips('當(dāng)前路徑內(nèi)無可播放的音樂文件')                return        pre_row = self.qlist.currentRow()-1 if self.qlist.currentRow() != 0 else self.qlist.count() - 1        self.qlist.setCurrentRow(pre_row)        self.is_switching = True        self.setCurPlaying()        self.playMusic()        self.is_switching = False'''下一首'''def nextMusic(self):        self.slider.setValue(0)        if self.qlist.count() == 0:                self.Tips('當(dāng)前路徑內(nèi)無可播放的音樂文件')                return        next_row = self.qlist.currentRow()+1 if self.qlist.currentRow() != self.qlist.count()-1 else 0        self.qlist.setCurrentRow(next_row)        self.is_switching = True        self.setCurPlaying()        self.playMusic()        self.is_switching = False

          雙擊某首歌切換:

          '''雙擊播放音樂'''def doubleClicked(self):        self.slider.setValue(0)        self.is_switching = True        self.setCurPlaying()        self.playMusic()        self.is_switching = False

          根據(jù)播放模式切換

          '''根據(jù)播放模式播放音樂'''def playByMode(self):        if (not self.is_pause) and (not self.is_switching):                self.slider.setMinimum(0)                self.slider.setMaximum(self.player.duration())                self.slider.setValue(self.slider.value() + 1000)        self.label1.setText(time.strftime('%M:%S', time.localtime(self.player.position()/1000)))        self.label2.setText(time.strftime('%M:%S', time.localtime(self.player.duration()/1000)))        # 順序播放        if (self.cmb.currentIndex() == 0) and (not self.is_pause) and (not self.is_switching):                if self.qlist.count() == 0:                        return                if self.player.position() == self.player.duration():                        self.nextMusic()        # 單曲循環(huán)        elif (self.cmb.currentIndex() == 1) and (not self.is_pause) and (not self.is_switching):                if self.qlist.count() == 0:                        return                if self.player.position() == self.player.duration():                        self.is_switching = True                        self.setCurPlaying()                        self.slider.setValue(0)                        self.playMusic()                        self.is_switching = False        # 隨機(jī)播放        elif (self.cmb.currentIndex() == 2) and (not self.is_pause) and (not self.is_switching):                if self.qlist.count() == 0:                        return                if self.player.position() == self.player.duration():                        self.is_switching = True                        self.qlist.setCurrentRow(random.randint(0, self.qlist.count()-1))                        self.setCurPlaying()                        self.slider.setValue(0)                        self.playMusic()                        self.is_switching = False
          All done~整體來說還是比較簡單的,大家可以參考代碼中的注釋進(jìn)行理解。

          代碼文件

          公眾號內(nèi)回復(fù)關(guān)鍵字:音樂播放器

          如果文章對你有幫助,歡迎轉(zhuǎn)發(fā)/點(diǎn)贊/收藏~

          作者:Charles未晞

          來源:Charles的皮卡丘


          _往期文章推薦_

          超不清視頻播放器




          如需了解付費(fèi)精品課程教學(xué)答疑服務(wù)
          請?jiān)?strong style="max-width: 100%;overflow-wrap: break-word !important;box-sizing: border-box !important;">Crossin的編程教室內(nèi)回復(fù): 666

          瀏覽 131
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  在线观看2区 | 日日夜夜精品一区 | 国产乱伦一区二区三区 | 噜噜吧噜噜久久综合 | 在线天堂资源19 |