Python -- 多媒体编程 -- 音乐播放

时间:2024-12-19 12:08:02

使用win32库的WMPlayer.OCX开发一个简易的音乐播放器

 import sys
 from PyQt4 import QtGui, QtCore
 from win32com.client import Dispatch

 class MyWindow(QtGui.QWidget):
     def __init__(self):
         super(MyWindow, self).__init__()
         self.setWindowTitle('音乐播放器')
         self.resize(485, 300)

         self.btnAdd = QtGui.QPushButton('Add')
         self.btnPlay = QtGui.QPushButton('Play')
         self.btnPause = QtGui.QPushButton('Pause')
         self.btnStop = QtGui.QPushButton('Stop')
         self.btnNext = QtGui.QPushButton('Next')
         self.txtList = QtGui.QTextEdit()

         grid = QtGui.QGridLayout()
         grid.addWidget(self.btnAdd, 0, 0)
         grid.addWidget(self.btnPlay, 0, 1)
         grid.addWidget(self.btnPause, 0, 2)
         grid.addWidget(self.btnStop, 0, 3)
         grid.addWidget(self.btnNext, 0, 4)
         grid.addWidget(self.txtList, 1, 0, 1, 5)
         self.setLayout(grid)

         self.connect(self.btnAdd, QtCore.SIGNAL('clicked()'), self.onBtnAdd)
         self.connect(self.btnPlay, QtCore.SIGNAL('clicked()'), self.onBtnPlay)
         self.connect(self.btnPause, QtCore.SIGNAL('clicked()'), self.onBtnPause)
         self.connect(self.btnStop, QtCore.SIGNAL('clicked()'), self.onBtnStop)
         self.connect(self.btnNext, QtCore.SIGNAL('clicked()'), self.onBtnNext)

         self.wmp = Dispatch('WMPlayer.OCX')

     def onBtnAdd(self):
         file = QtGui.QFileDialog.getOpenFileName(self, '打开文件', filter='音乐文件(*.mp3; *.wma; *.wav)')
         if file:
             media = self.wmp.newMedia(file)
             self.wmp.currentPlayList.appendItem(media)
             self.txtList.append(file+'\n')
     def onBtnPlay(self):
         self.wmp.controls.play()
     def onBtnPause(self):
         self.wmp.controls.pause()
     def onBtnStop(self):
         self.wmp.controls.stop()
     def onBtnNext(self):
         self.wmp.controls.next()
 app = QtGui.QApplication(sys.argv)
 mywindow = MyWindow()
 mywindow.show()
 app.exec_()

Python -- 多媒体编程 -- 音乐播放