PyQt5 简单Mp3播放器--QMediaPlayer
2019-08-25 python 3225
import sys from PyQt5.QtWidgets import QWidget,QApplication,QPushButton,QSlider,QLabel from PyQt5.QtMultimedia import QMediaPlayer,QMediaContent from PyQt5.QtCore import QUrl,Qt import os class Mp3(QWidget): def __init__(self): super().__init__() self.initUI() self.control_flag = 0 def formatTime(self,num): num = int(num) if num>0: min = str(int(num/60+100))[1:3] sec = str(int(num%60+100))[1:3] return "%s:%s" % (str(min),str(sec)) return "00:00" def initUI(self): mp3file = "yhbk.mp3" self.player = QMediaPlayer() self.player.setMedia(QMediaContent(QUrl.fromLocalFile(mp3file))) self.player.play() mp3_lbl = QLabel(os.path.basename(mp3file),self) mp3_lbl.move(100, 30) #mp3 时长 self.time_lbl = QLabel(self) self.time_lbl.move(130, 60) self.volume_slider = QSlider(self) self.volume_slider.resize(10,50) self.volume_slider.move(240,80) self.volume_slider.valueChanged[int].connect(self.volume) self.player.setVolume(25) self.volume_lbl = QLabel("25",self) self.volume_lbl.move(240, 130) self.play_slider = QSlider(Qt.Horizontal,self) self.play_slider.resize(200,20) self.play_slider.move(30,80) self.play_slider.sliderPressed.connect(self.setControlIn) self.play_slider.sliderReleased.connect(self.setControlOut) self.play_slider.sliderMoved.connect(self.setControlIn) self.player.pause() self.actionbtn = QPushButton("暂停",self) self.actionbtn.move(100, 130) self.actionbtn.clicked.connect(self.action) # 信号、槽 self.player.positionChanged.connect(self.playState) self.player.durationChanged.connect(self.playTime) self.setGeometry(300,300,300,200) self.setWindowTitle("Mp3") # 按下 def setControlIn(self): self.control_flag = 1 #离开 def setControlOut(self): self.control_flag = 0 time = int(self.player.duration() / 1000) pos = int(self.play_slider.value()/100*time*1000) self.player.setPosition(pos) #播放位置 def playState(self): dur = int(self.player.position()/1000) time = int(self.player.duration()/1000) self.time_lbl.setText("%s/%s" % (self.formatTime(dur), self.formatTime(time))) self.time_lbl.adjustSize() #控制进度 if self.control_flag == 0: self.play_slider.setValue(int(dur/time*100)) def playTime(self): time = int(self.player.duration()/1000) self.time_lbl.setText("%s/%s" %(self.formatTime(0),self.formatTime(time))) self.time_lbl.adjustSize() def volume(self,num): self.player.setVolume(num) self.volume_lbl.setText(str(num)) self.volume_lbl.adjustSize() def action(self): if self.actionbtn.text() == "播放": self.actionbtn.setText("暂停") self.player.pause() else: self.actionbtn.setText("播放") self.player.play() if __name__ =="__main__": app = QApplication(sys.argv) ex = Mp3() ex.show() sys.exit(app.exec_())
很赞哦! (0)
相关文章
文章评论
-
-
-
0条评论