使用python + pyqt实现的音乐播放器。包括音乐播放和暂停,进度条控制功能。
1.界面设计
1.1 摆放组件
使用QtDesinger,将需要的UI组件摆放好
(1)整体为水平布局,左边为图片,右边为垂直布局的其他组件
(2)右边整体为垂直布局,有三行,第一行是标题lable,第二行是水平布局的进度条和时间显示,第三行是水平布局的音量条和按钮
(3)第二行是水平布局的进度条和时间lable
(4)第三行是音量条和按钮,由于要居右放置,因此左侧有一个空白的lable用于占位
1.2 调整组件尺寸
最终效果
1.3 导出为python代码
QtDesigner导出为python代码,Ui_untitled.py文件
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def __init__(self,music_player_obj):
self.song_formats = ['mp3', 'm4a', 'flac', 'wav', 'ogg']
self.songs_list = []
self.cur_playing_song = ''
self.is_pause = True
self.cur_music_path = ''
self.music_player_obj = music_player_obj
self.MainWindow = None
pass
def setupUi(self, MainWindow):
self.MainWindow = MainWindow
MainWindow.setObjectName("MainWindow")
MainWindow.resize(820, 125)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(9, 9, 781, 81))
self.layoutWidget.setObjectName("layoutWidget")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget)
self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_2.setSpacing(5)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.logo_lable = QtWidgets.QLabel(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(1)
sizePolicy.setVerticalStretch(1)
sizePolicy.setHeightForWidth(self.logo_lable.sizePolicy().hasHeightForWidth())
self.logo_lable.setSizePolicy(sizePolicy)
self.logo_lable.setText("")
self.logo_lable.setPixmap(QtGui.QPixmap("e:\\myCode\\py-music-player\\res/music_icon.png"))
self.logo_lable.setObjectName("logo_lable")
self.horizontalLayout_2.addWidget(self.logo_lable)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.verticalLayout.setSpacing(0)
self.verticalLayout.setObjectName("verticalLayout")
self.music_title = QtWidgets.QLabel(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.music_title.sizePolicy().hasHeightForWidth())
self.music_title.setSizePolicy(sizePolicy)
self.music_title.setObjectName("music_title")
self.verticalLayout.addWidget(self.music_title,0, QtCore.Qt.AlignHCenter)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.horizontalLayout_3.setContentsMargins(0, -1, -1, -1)
self.horizontalLayout_3.setSpacing(20)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.progress_slider = QtWidgets.QSlider(self.layoutWidget)
self.progress_slider.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.progress_slider.sizePolicy().hasHeightForWidth())
self.progress_slider.setSizePolicy(sizePolicy)
self.progress_slider.setMinimumSize(QtCore.QSize(0, 0))
self.progress_slider.setOrientation(QtCore.Qt.Horizontal)
self.progress_slider.setObjectName("progress_slider")
self.horizontalLayout_3.addWidget(self.progress_slider)
self.progress_lable = QtWidgets.QLabel(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.progress_lable.sizePolicy().hasHeightForWidth())
self.progress_lable.setSizePolicy(sizePolicy)
self.progress_lable.setObjectName("progress_lable")
self.horizontalLayout_3.addWidget(self.progress_lable)
self.horizontalLayout_3.setStretch(0, 9)
self.horizontalLayout_3.setStretch(1, 1)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.horizontalLayout.setSpacing(12)
self.horizontalLayout.setObjectName("horizontalLayout")
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
self.label = QtWidgets.QLabel(self.layoutWidget)
self.label.setText("")
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.volume_slider = QtWidgets.QSlider(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.volume_slider.sizePolicy().hasHeightForWidth())
self.volume_slider.setSizePolicy(sizePolicy)
self.volume_slider.setOrientation(QtCore.Qt.Horizontal)
self.volume_slider.setObjectName("volume_slider")
self.horizontalLayout.addWidget(self.volume_slider)
self.play_btn = QtWidgets.QPushButton(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.play_btn.sizePolicy().hasHeightForWidth())
self.play_btn.setSizePolicy(sizePolicy)
self.play_btn.setObjectName("play_btn")
self.horizontalLayout.addWidget(self.play_btn)
self.openmusic_btn = QtWidgets.QPushButton(self.layoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.openmusic_btn.sizePolicy().hasHeightForWidth())
self.openmusic_btn.setSizePolicy(sizePolicy)
self.openmusic_btn.setObjectName("openmusic_btn")
self.horizontalLayout.addWidget(self.openmusic_btn)
self.horizontalLayout.setStretch(0, 2)
self.horizontalLayout.setStretch(3, 2)
self.horizontalLayout.setStretch(4, 2)
self.verticalLayout.addLayout(self.horizontalLayout)
self.verticalLayout.setStretch(0, 1)
self.verticalLayout.setStretch(1, 1)
self.verticalLayout.setStretch(2, 10)
self.horizontalLayout_2.addLayout(self.verticalLayout)
self.horizontalLayout_2.setStretch(1, 10)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 889, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.openmusic_btn.clicked.connect(self.music_player_obj.on_btn_openmusic)
self.play_btn.clicked.connect(self.music_player_obj.on_btn_playMusic)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.music_title.setText(_translate("MainWindow", "请打开音乐"))
self.progress_lable.setText(_translate("MainWindow", "00:00/00:00"))
self.play_btn.setText(_translate("MainWindow", "播放"))
self.openmusic_btn.setText(_translate("MainWindow", "打开"))
def Tips(self, message):
QtWidgets.QMessageBox.about(self.MainWindow, "提示", message)
2.功能实现
创建主程序文件main.py,初始化界面并启动界面程序
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
import Ui_untitled
import music_player
print("Hello World")
if __name__ == '__main__':
app = QApplication(sys.argv)
MainWindow = QMainWindow()
music_player = music_player.music_player()
ui = Ui_untitled.Ui_MainWindow(music_player)
ui.setupUi(MainWindow)
music_player.set_ui_obj(ui)
MainWindow.show()
sys.exit(app.exec_())
创建music_player.py文件,用于实现按钮功能
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtCore import QUrl, QTimer
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
import time
class music_player():
ui_obj = None
def __init__(self):
self.player = QMediaPlayer()
self.is_switching = False
self.ui_obj = None
self.cur_music_path =''
self.is_pause = True
self.is_switching = False
self.setup_grogress_slider()
#获取到UI对象,顺便将进度条归零
def set_ui_obj(self,ui_obj):
self.ui_obj = ui_obj
self.ui_obj.progress_slider.sliderMoved[int].connect(lambda: self.player.setPosition(self.ui_obj.progress_slider.value()))
#"打开"按钮的功能实现
def on_btn_openmusic(self):
print("on btn openmusic")
music_path = QFileDialog.getOpenFileName(None,"选取音乐文件",'./')
self.cur_music_path = music_path[0]
music_title = self.cur_music_path.split('/')[-1].split('.')[0]
print(self.cur_music_path)
self.ui_obj.music_title.setText(music_title)
self.setCurPlaying()
#弹出提示窗口
def Tips(self, message):
self.ui_obj.Tips(message)
#设置当前播放文件
def setCurPlaying(self):
self.player.setMedia(QMediaContent(QUrl(self.cur_music_path)))
#播放/暂停按钮的功能实现
def on_btn_playMusic(self):
print("in on_btn_playMusic")
if not self.cur_music_path:
self.Tips('当前无可播放的音乐文件')
return
if not self.player.isAudioAvailable():
self.Tips('当前无可播放的音乐文件')
return
if self.is_pause:
self.player.play()
self.is_pause = False
self.ui_obj.play_btn.setText('暂停')
elif (not self.is_pause):
self.player.pause()
self.is_pause = True
self.ui_obj.play_btn.setText('播放')
self.update_progress_slider()
#设置并启动进度条定时器,每一秒刷新一次进度条
def setup_grogress_slider(self):
self.timer = QTimer(self.ui_obj)
self.timer.start(1000)
self.timer.timeout.connect(self.update_progress_slider)
#更新进度条位置
def update_progress_slider(self):
#没有歌曲时不更新进度条
if not self.player.isAudioAvailable():
return
# 刷新进度条
if (not self.is_pause):
self.ui_obj.progress_slider.setMinimum(0)
self.ui_obj.progress_slider.setMaximum(self.player.duration())
self.ui_obj.progress_slider.setValue(self.ui_obj.progress_slider.value() + 1000)
print("music pos:%s"%self.player.position())
self.ui_obj.progress_lable.setText(time.strftime('%M:%S', time.localtime(self.player.position()/1000)))