def __init__(self, *args, **kwargs): QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) self.setWindowIcon(QIcon(LOCAL_DIR + '/ytdl_music.svg')) self.player = QMediaPlayer() self.player.isSeekable() self.playList = QMediaPlaylist() self.playListData = [] self.player.setPlaylist(self.playList) self.currentPos = 0 self.currentTrackDuration = '0:00:00' self.player.positionChanged.connect(self.positionChanged) self.player.durationChanged.connect(self.durationChanged) self.playList.currentIndexChanged.connect(self.playlistPosChanged) self.playlistTable.itemDoubleClicked.connect(self.changeTrack) self.playlistTable.itemSelectionChanged.connect(self.selectedTracks) # self.timeSlider.valueChanged.connect(self.setPosition) self.addBtn.clicked.connect(self.addDialog) self.removeBtn.clicked.connect(self.delTracks) self.playBtn.clicked.connect(self.playPause) self.stopBtn.clicked.connect(self.stop) self.prevBtn.clicked.connect(self.playList.previous) self.nextBtn.clicked.connect(self.playList.next) self.playlistTable.setHorizontalHeaderLabels([ '', _translate('MainWindow', 'Channel'), _translate('MainWindow', 'Title') ]) header = self.playlistTable.horizontalHeader() header.setSectionResizeMode(1, QHeaderView.Stretch) header.setSectionResizeMode(2, QHeaderView.Stretch)
def showMainWindow(self): self.move((self.screen.width() - self.width()) / 2, (self.screen.height() - self.height()) / 2) self.meidaPlayer = QMediaPlayer() self.playlist = QMediaPlaylist() self.playlist.setCurrentIndex(1) self.playlist.addMedia( QMediaContent(QUrl().fromLocalFile( "video/Radio-Digital-Scheme-Live-Wallpaper~1.mp4"))) self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop) self.meidaPlayer.setPlaylist(self.playlist) videoWidget = QVideoWidget() videoWidget.setAspectRatioMode(Qt.IgnoreAspectRatio) videoWidget.setAutoFillBackground(True) videoWidget.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) # videoWidget.setMinimumSize(videoWidget.size()) self.meidaPlayer.setVideoOutput(videoWidget) self.videoLayout.insertWidget(0, videoWidget) self.meidaPlayer.play() # self.pushButton_4.clicked.connect(self.showColorDialog) self.pushButton_4.installEventFilter(self) # self.pushButton.setGeometry() self.setVisible(1)
def __init__(self): super(Game, self).__init__() self.scene = PlayGround() self.scene.setBackgroundBrush( QBrush(QImage(":/Resources/images/BackGround.png"))) self.view = PlayGroundView() self.view.setScene(self.scene) self.player = Player() self.addToGround(self.player) self.tower = Tower() self.addToGround(self.tower) self.gameObjectPosition(self.tower, 200, 450) # self.alien = Alien() # self.addToGround(self.alien) self.backgroundMusic = QMediaPlayer() self.playList = QMediaPlaylist() self.playList.addMedia( QMediaContent(QUrl("qrc:/Resources/sounds/Game_Background.mp3"))) self.playList.setPlaybackMode(QMediaPlaylist.Loop) self.backgroundMusic.setPlaylist(self.playList) self.backgroundMusic.setVolume(2) self.backgroundMusic.play() self.changeFocus(self.player) self.gameObjectPosition(self.player, 750 / 2, 550) self.setSize() self.spawnEnemies()
class VideoPlayer(QMainWindow): def __init__(self): super(VideoPlayer, self).__init__() self._screen_size = QApplication.primaryScreen().size() sw, sh = self._screen_size.width(), self._screen_size.height() self.resize(sw, sh) self.setStyleSheet('background: black') # # PLAYER self._playList = QMediaPlaylist() self._playWidget = QVideoWidget(self) self._playWidget.resize(sw, sh) self._player = QMediaPlayer(self) self._player.setPlaylist(self._playList) self._player.setVideoOutput(self._playWidget) self._playList.addMedia(QMediaContent( QUrl.fromLocalFile('/Users/huangkai/Documents/PycharmProjects/AllTest/Qt插入背景/AddVideos/Videos/yellow.mov'))) self._playList.setPlaybackMode(QMediaPlaylist.Loop) self._player.play() def keyPressEvent(self, a0: QKeyEvent) -> None: key = a0.key() if key == Qt.Key_Escape: self.resize(100, 100) self._playWidget.resize(100, 100) self._player.stop() elif key in (Qt.Key_Return, Qt.Key_Enter): self.resize(self._screen_size.width(), self._screen_size.height())
class VideoPlayer(QVideoWidget): def __init__(self): super(VideoPlayer, self).__init__() self._player = QMediaPlayer() self._playlist = QMediaPlaylist() self._stopped = True # プレイリストに動画を追加 def addMedia(self, media_file): media_content = QMediaContent(QUrl.fromLocalFile(media_file)) self._playlist.addMedia(media_content) # クリックでポーズ・再生の切り替え def mousePressEvent(self, event): if self._stopped: self.play() else: self._player.pause() self._stopped = True # ダブルクリックで動画を読み込み,再生 def mouseDoubleClickEvent(self, event): self._player.setVideoOutput(self) self._player.setPlaylist(self._playlist) self.play() def play(self): self._player.play() self._stopped = False
def openMultipleFile(self): dialogs = QFileDialog(self) self.fnames, _ = dialogs.getOpenFileNames( self, 'Open Media Files', QDir.homePath(), "Videos (*.mp4 *.mkv *.3pg)") if self.fnames != '': self.playlist = QMediaPlaylist(self) self.fnamelist = [] for playlst in self.fnames: self.fnamelist.append( QMediaContent(QUrl.fromLocalFile(playlst))) self.playlist.addMedia(self.fnamelist) self.playlist.setCurrentIndex(1) self.videoWidget = QVideoWidget(self) self.mediaPlayer.setVideoOutput(self.videoWidget) # self.videoWidget.setAspectRatioMode(60, 60,Qt.KeepAspectRatioByExpanding) self.mediaPlayer.setPlaylist(self.playlist) self.playlist.currentIndexChanged.connect(self.mediaNameChange) self.mediaPlayer.play() self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPause)) self.play.setEnabled(True) self.stop.setEnabled(True) self.loop.setEnabled(True) if (len(self.fnamelist) > 1): self.forw.setEnabled(True) self.shuffl.setEnabled(True) self.l1.setText("00:00") mediaName = self.fnames[0].rsplit('/', 1)[-1] self.fulltitle = mediaName + " - " + self.titles self.setWindowTitle(self.fulltitle) self.mediaPlayer.durationChanged.connect(self.sliderDuration)
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.playlistView = QListView() self.switch_status = 2 self.video_widget = QVideoWidget() self.playlist = QMediaPlaylist() self.model = PlaylistModel(self.playlist) self.titleBar = TitleBar(self) self.currentTimeLabel = QLabel() self.timeSlider = QSlider() self.totalTimeLabel = QLabel() self.mediaPlayer = QMediaPlayer() self.open_btn = QPushButton('Open File') self.play_btn = QPushButton() self.prev_btn = QPushButton() self.stop_btn = QPushButton() self.next_btn = QPushButton() self.switch_media_widgets_btn = QPushButton() self.pseudo_label = QLabel() self.vol_label = QLabel() self.volume_slider = Slider(Qt.Horizontal) self.gui() self.set_children_focus_policy(Qt.NoFocus)
def init_video_background(self): """Creates/configures the PyQt5 objects necessary to launch the video background of the application. A new QVideoWidget is passed to a QMediaPlayer object ( a general media playback object in PyQt5). The QMediaPlayer is configured as a 'VideoSurface' for video compatibility. The url to the video background is passed to a QMediaPlaylist set to loop. The video_playlist is then passed to the QMediaPlayer and playback starts. """ self.video_widget = QVideoWidget() # QVideoWidget must be set as Central Widget to play in background - otherwise it plays in a separate window self.setCentralWidget(self.video_widget) self.video_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.video_player.setVideoOutput(self.video_widget) self.video_playlist = QMediaPlaylist() self.video_playlist.setCurrentIndex(0) self.video_playlist.setPlaybackMode(QMediaPlaylist.Loop) self.video_playlist.addMedia( QMediaContent( QUrl.fromLocalFile('./media/video/background_video.mp4'))) self.video_player.setPlaylist(self.video_playlist) self.video_player.play()
def play_files(self, filepaths): playlist = QMediaPlaylist(self.player) for filepath in filepaths: url = QUrl.fromLocalFile(filepath) playlist.addMedia(QMediaContent(url)) self.player.setPlaylist(playlist) self.player.play()
def __init__(self, parent=None): super(BackWindow, self).__init__(parent) self.init_ui() self.w = None self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.main_mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) # self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.durationChanged.connect(self.durationChanged) self.mediaPlayer.error.connect(self.handleError) self.main_mediaPlayer.positionChanged.connect(self.positionChanged) self.main_mediaPlayer.durationChanged.connect(self.durationChanged) self.main_mediaPlayer.error.connect(self.handleError) self._playlist = QMediaPlaylist() #self.addMedia("movie/movie1.wmv") self.init_play_list() self._stopped = True self.mediaPlayer.setVideoOutput(self.ui.videoWidget) self.mediaPlayer.setPlaylist(self._playlist) self.main_mediaPlayer.setPlaylist(self._playlist)
class chirpyPlayer(QMediaPlayer): def __init__(self): super().__init__() self._prevSong=0 self._skipped=False self._playlist=QMediaPlaylist(self) self.setPlaylist(self._playlist) self.currentMediaChanged.connect(self.unsetSkipped) def replacePlaylist(self,plist): self._playlist.clear() for i in range (plist.rowCount()): self._playlist.addMedia(QMediaContent(QUrl.fromLocalFile( plist.data(plist.index(i,0),Qt.UserRole)))) def setSkipped(self): self._skipped=True def unsetSkipped(self): self._skipped=False @pyqtProperty(bool) def skipped(self): return self._skipped @skipped.setter def skipped(self, val): self._skipped = bool(val) @pyqtProperty(int) def previousId(self): return self._prevSong @previousId.setter def previousId(self, id): self._prevSong=id
def init_public(self): # 时间日期显示label 第一行 >>>>>>> self.time_show = QtCore.QTimer() self.time_show.start(100) self.time_show.timeout.connect(self.time_show_out) self.label_0_time = QLabel() self.setObjectName('label_0_time') self.label_0_time.setStyleSheet("QLabel{color: white ; background-color: 1}") self.label_0_time.setEnabled(False) font_time = QtGui.QFont() font_time.setFamily("楷体") font_time.setPointSize(10) self.label_0_time.setFont(font_time) self.label_0_time.setFixedSize(QtCore.QSize(180, 15)) # self.gridLayout.addWidget(self.label_0_time, 0,2,1,1) #self.label_0_time.setEnabled(False) self.gridLayout.addWidget(self.label_0_time, 0, 5, 1, 1) # 公共音频接口 self.play_common_list = QMediaPlaylist() self.play_common_player = QMediaPlayer() self.play_common_player.setPlaylist(self.play_common_list) self.play_common_player.stateChanged.connect(self.play_common_player_stateChanged) ## 主布局 self.gridLayout.addWidget(self.tabWidget, 1, 0, 1, 12) self.setLayout(self.gridLayout) self.tabWidget.setCurrentIndex(0)
class VideoPlayer(QVideoWidget): def __init__(self): super(VideoPlayer, self).__init__() self._player = QMediaPlayer() self._playlist = QMediaPlaylist() self._stopped = True # プレイリストに動画を追加 def addMedia(self, media_file): media_content = QMediaContent(QUrl.fromLocalFile(media_file)) self._playlist.addMedia(media_content) # クリックでポーズ・再生の切り替え def mousePressEvent(self, event): if self._stopped: self.play() else: self._player.pause() self._stopped = True # ダブルクリックで動画を読み込み,再生 def mouseDoubleClickEvent(self, event): self._player.setVideoOutput(self) self._player.setPlaylist(self._playlist) self.play() def play(self): self._player.play() self._stopped = False
class SoundPack: def __init__(self, name, bg, shoot, hit, score_up, swap, loose, win): """ Creates Soundpack name - soundpack name other params - non-absolute way to files """ self.name = name self.back = QMediaPlaylist() for sound in bg: url = QUrl.fromLocalFile(os.path.join(os.getcwd(), sound)) self.back.addMedia(QMediaContent(url)) self.back.setPlaybackMode(QMediaPlaylist.Loop) self.bg = QMediaPlayer() self.bg.setPlaylist(self.back) self.bg.setVolume(30) self.shoot = QSound(shoot) self.hit = QSound(hit) self.score_up = QSound(score_up) self.swap = QSound(swap) self.loose = QSound(loose) self.win = QSound(win)
def __init__(self, parent=None): # 主窗口界面 super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setFixedSize(800, 600) self.difficulty = 3 # 难度 self.setWindowTitle('小学算术题 难度:%d' % self.difficulty) self.setWindowIcon(QIcon('res/image/windowIcon.jpg')) self.ui.pauseBtn.setIcon(QIcon('res/image/pause.png')) # 设置窗口界面 self.setting = Setting() self.setting._close_signal.connect(self.on_setting_closed) # 音效加载 self.playlist = QMediaPlaylist() self.playlist.addMedia(QMediaContent(QUrl('res/audio/correct.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/wrong.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/complete.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/timeOver.mp3'))) self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemOnce) self.player = QMediaPlayer() self.player.setPlaylist(self.playlist) self.player.play() # 定义变量 self.answer = 0 self.total = 0 self.correct = 0 self.accuracy = 0. self.overtime = 0 self.tmpOutput = [] # 保存路径 self.fpath = 'history.txt' # 定时器初始化 self.timeLimit = 30 self.timer = QTimer(self) self.timer.timeout.connect(self.on_timer_timeout) self.currentTime = self.timeLimit self.ui.timeLabel.setText(str(self.currentTime)) self.pause = False # 错题模式初始化 self.mistakeBatchSize = 5 self.mistakeMode = False self.exitingMistakeMode = False self.ui.tipLabel.clear() self.ui.remainingLabel.clear() self.questionQueue = [] # 第一次开始运行 self.refreshQuestion() self.refreshBoard() # 计时器开始计时 self.timer.start(1000)
def __init__(self): super().__init__() self.player = QMediaPlayer() # 播放器 self.playlist = QMediaPlaylist() # 播放列表 self.title = '音乐播放器' self.volumeHint = QLabel('音量: 99%') self.mInfo = { 'cover': './default_cover.jpg', 'music': '', 'singer': '', 'duration': 0 } self.aboutWin = AboutWindow() self.cover = QLabel() self.listWid = QListWidget() # 设置主窗口位置 self.left = 200 self.top = 100 self.width = 500 self.height = 430 self.font = QFont('SansSerif', 10.5) self.color = 1 # 0 - 黑色界面, 1 - 白色界面 self.userAction = 0 # 0 - 停止中, 1 - 播放中 2 - 暂停中 self.initUI()
def __init__(self): super().__init__() self.audio_list_widget = QListWidget() self.audio_list_widget.installEventFilter(self) self.audio_list_widget.itemDoubleClicked.connect(self.play) # TODO: playlist объединить с audio_list_widget (см примеры работы с QMediaPlayer) self.playlist = QMediaPlaylist() self.playlist.currentIndexChanged.connect( lambda row: self.audio_list_widget.setCurrentRow(row)) # TODO: обрабатывать сигналы плеера: http://doc.qt.io/qt-5/qmediaplayer.html#signals self.player = QMediaPlayer() self.player.setPlaylist(self.playlist) self.player.currentMediaChanged.connect( lambda media: self.about_play_audio.emit(self.audio_list_widget. currentItem().text())) if not self.player.isAvailable(): # TODO: перевод text = "The QMediaPlayer object does not have a valid service.\n" \ "Please check the media service plugins are installed." log.warning(text) QMessageBox.warning(self, "Service not available", text) quit() self.controls = PlayerControls(self.player) self.controls.set_state(self.player.state()) self.controls.set_volume(self.player.volume()) self.controls.set_muted(self.controls.is_muted()) self.controls.play_signal.connect(self.play) self.controls.pause_signal.connect(self.player.pause) self.controls.stop_signal.connect(self.player.stop) self.controls.next_signal.connect(self.playlist.next) self.controls.previous_signal.connect(self.playlist.previous) self.controls.change_volume_signal.connect(self.player.setVolume) self.controls.change_muting_signal.connect(self.player.setMuted) self.progress = QProgressBar() self.progress.hide() layout = QVBoxLayout() layout.addWidget(self.controls) layout.addWidget(self.audio_list_widget) layout.addWidget(self.progress) self.setLayout(layout) self.thread = LoadAudioListThread() self.thread.about_add_audio.connect(self._add_audio) self.thread.about_progress.connect(self.progress.setValue) self.thread.about_range_progress.connect(self.progress.setRange) self.thread.started.connect(self._start) self.thread.finished.connect(self._finished)
def __init__(self, api_key): super().__init__(flags=QMediaPlayer.VideoSurface) self._playlist = QMediaPlaylist() self._api_key = api_key self._download_threads = [] self._cache_path = Path(os.getenv('appdata')) / 'MilkPlayer' self._metadata_file = self._cache_path / 'metadata.json' self.setPlaylist(self._playlist) self.currentMediaChanged.connect(self._set_nowplaying)
def __init__(self, args=(), kwargs=None): super().__init__() self.media_player = QMediaPlayer(flags=QMediaPlayer.LowLatency) self.playlist = QMediaPlaylist() self.media_player.setPlaylist(self.playlist) self._priority = 0 # For play on non-Windows platforms: mixer.init() self.pygame_player = mixer.music
class PlayVideo(DisplayEvent): def __init__(self, frame, settings): super().__init__(frame, settings) self.url = QUrl(settings.get("url")) self.start_time = settings.get("start", 0) * 1000 self.duration = settings.get("duration") self.loop = settings.get("loop", True) self.volume = settings.get("volume", 100) self.playback_rate = settings.get("playbackRate", 1.0) def do_tick(self): if self.player: self.logging.info("position: %s/%s status: %s error: %s" % ( self.player.position(), self.player.duration(), self.player.mediaStatus(), self.player.errorString(), )) if self.player.errorString(): self.logging.error(self.player.errorString()) self.cancel() def do_initialize(self): super().do_initialize() self.video = QVideoWidget(self.widget) self.add_widget(self.video) self.video.show() self.media = QMediaContent(self.url) self.playlist = QMediaPlaylist(self.video) self.playlist.addMedia(self.media) self.playlist.setPlaybackMode( QMediaPlaylist.Loop if self.loop else QMediaPlaylist.Sequential) self.player = QMediaPlayer(self.widget) self.player.setVideoOutput(self.video) self.player.setVolume(self.volume) self.player.setPlaybackRate(self.playback_rate) def do_run(self): super().do_run() self.player.setPlaylist(self.playlist) self.player.setPosition(self.start_time) self.player.play() if self.player.errorString(): self.logging.error(self.player.errorString()) self.cancel() def do_stop(self): super().do_stop() self.player.stop() def do_reset(self): self.player = None self.video = None
def __init__(self): super().__init__() self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.setWindowTitle('Musix') self.left, self.top, self.width, self.height = 300,300,640,200 self. color = 0 # 0 - toggle to dark, 1 - toggle to light self.userAction = -1 # 0 - stopped, 1 - playing, 2 - paused self.initUI()
def playFile(self, videoPath): ''' Play file from path ''' try: RemoveVideoLayers() RemoveGroupByName() # settrace() # if "udp://" in videoPath: # host, port = videoPath.split("://")[1].split(":") # receiver = UDPClient(host, int(port), type="udp") # receiver.show() # self.close() # return # if "tcp://" in videoPath: # host, port = videoPath.split("://")[1].split(":") # receiver = UDPClient(host, port, type="tcp") # receiver.show() # self.close() # return self.fileName = videoPath self.playlist = QMediaPlaylist() url = QUrl.fromLocalFile(videoPath) self.playlist.addMedia(QMediaContent(url)) self.player.setPlaylist(self.playlist) self.setWindowTitle( QCoreApplication.translate("QgsFmvPlayer", 'Playing : ') + os.path.basename(os.path.normpath(videoPath))) if self.HasMetadata(videoPath): CreateVideoLayers() self.clearMetadata() self.lb_cursor_coord.setText( "<span style='font-size:10pt; font-weight:bold;'>Lon :</span>" + "<span style='font-size:9pt; font-weight:normal;'>Null</span>" + "<span style='font-size:10pt; font-weight:bold;'> Lat :</span>" + "<span style='font-size:9pt; font-weight:normal;'>Null</span>" ) else: self.btn_GeoReferencing.setEnabled(False) self.HasFileAudio = True if not self.HasAudio(videoPath): self.actionAudio.setEnabled(False) self.actionSave_Audio.setEnabled(False) self.HasFileAudio = False self.playClicked(True) except Exception as e: qgsu.showUserAndLogMessage(QCoreApplication.translate( "QgsFmvPlayer", 'Open Video File : '), str(e), level=QGis.Warning)
def __init__(self, iface, path=None, parent=None): """ Constructor """ super(QgsFmvPlayer, self).__init__(parent) self.setupUi(self) self.parent = parent self.iface = iface self.fileName = None self.metadataDlg = None self.createingMosaic = False self.currentInfo = 0.0 self.RecGIF = QMovie(":/imgFMV/images/record.gif") self.videoWidget2.setVisible(False) self.resize(730, 350) self.videoWidget.customContextMenuRequested[QPoint].connect( self.contextMenuRequested) # self.videoWidget2.customContextMenuRequested[QPoint].connect( # self.contextMenuRequested) self.duration = 0 self.playerMuted = False self.HasFileAudio = False self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.player.setNotifyInterval(700) # Metadata Callback Interval self.pass_time = 0.08 self.playlist = QMediaPlaylist() self.player.setVideoOutput( self.videoWidget.videoSurface()) # Abstract Surface # self.player.setVideoOutput( # self.videoWidget2) # Standar Surface self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.stateChanged.connect(self.setCurrentState) self.playerState = QMediaPlayer.StoppedState self.playFile(path) self.sliderDuration.setRange(0, self.player.duration() / 1000) self.volumeSlider.setValue(self.player.volume()) self.volumeSlider.enterEvent = self.showVolumeTip if self.metadataDlg is None: self.metadataDlg = QgsFmvMetadata(parent=self, player=self) self.addDockWidget(Qt.RightDockWidgetArea, self.metadataDlg) self.metadataDlg.setMinimumWidth(500) self.metadataDlg.hide()
def __init__(self): super(music_play, self).__init__() #调用该类的父类的初始化函数,完成窗口布局操作 self.setupUi(self) self.setWindowTitle("VIP音乐播放器") self.setWindowIcon(QIcon("format.ico")) #self.SaveData = db() self.m_filepath = 'E:/MusicMedia/MusicMedia/music/' self.player = QMediaPlayer() self.PlayList = QMediaPlaylist() self.player.setPlaylist(self.PlayList)
def __init__(self, path): super().__init__() if path: sound = QMediaContent(QUrl.fromLocalFile(get_path(path))) self.setMedia(sound) else: play_list = QMediaPlaylist() play_list.setPlaybackMode(QMediaPlaylist.Sequential) self.setPlaylist(play_list) self.play_list = play_list
def __init__(self, parent): # 윈도우 객체 self.parent = parent self.player = QMediaPlayer() self.player.currentMediaChanged.connect(self.mediaChanged) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.playlist = QMediaPlaylist()
def __init__(self): super(play, self).__init__() self.setupUi(self) self.setWindowTitle("VIP音乐播放器") self.m_filepath = 'E:/MusicMedia/MusicMedia/music/' # self.m_filepath = 'E:/ProgramData/PyUI/music' self.player = QMediaPlayer() self.PlayList = QMediaPlaylist() self.player.setPlaylist(self.PlayList) self.count = 0 #做一个计数器
def __init__(self, welcomeVid): super(self.__class__, self).__init__() self.setupUi(self) self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.pList = QMediaPlaylist() media = QUrl("file://" + welcomeVid) self.pList.addMedia(QMediaContent(media)) self.player.setPlaylist(self.pList) self.pList.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop) self.player.setVideoOutput(self.welcomeVideo)
def setup_music(self): self.music = QMediaPlayer() self.playlist = QMediaPlaylist() self.playlist.setPlaybackMode(QMediaPlaylist.Loop) file_name = "sound/bg.mp3" self.media = QMediaContent(QUrl.fromLocalFile(file_name)) self.playlist.addMedia(self.media) self.music.setPlaylist(self.playlist) self.music.setVolume(20) self.music.play()
def playFile(self, videoPath): ''' Play file from path ''' try: RemoveVideoLayers() RemoveGroupByName() # if "udp://" in videoPath: # host, port = videoPath.split("://")[1].split(":") # receiver = UDPClient(host, int(port), type="udp") # receiver.show() # self.close() # return # if "tcp://" in videoPath: # host, port = videoPath.split("://")[1].split(":") # receiver = UDPClient(host, port, type="tcp") # receiver.show() # self.close() # return self.fileName = videoPath self.playlist = QMediaPlaylist() if self.isStreaming: url = QUrl(videoPath) else: url = QUrl.fromLocalFile(videoPath) qgsu.showUserAndLogMessage("", "Added: " + str(url), onlyLog=True) self.playlist.addMedia(QMediaContent(url)) self.player.setPlaylist(self.playlist) self.setWindowTitle( QCoreApplication.translate("QgsFmvPlayer", 'Playing : ') + os.path.basename(os.path.normpath(videoPath))) CreateVideoLayers() self.clearMetadata() self.HasFileAudio = True if not self.HasAudio(videoPath): self.actionAudio.setEnabled(False) self.actionSave_Audio.setEnabled(False) self.HasFileAudio = False # Recenter map on video initial point if self.initialPt: rect = QgsRectangle(self.initialPt[1], self.initialPt[0], self.initialPt[1], self.initialPt[0]) self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().refresh() self.playClicked(True) except Exception as e: qgsu.showUserAndLogMessage(QCoreApplication.translate( "QgsFmvPlayer", 'Open Video File : '), str(e), level=QGis.Warning)
def _contentPlay(self, checked): if self.curDictWord is None: return self.stop_voice_play() if self.curWord.content_voices: mp3list = [os.path.join(self.curDictWord.data_path, fname) for fname in self.curWord.content_voices] playlist = QMediaPlaylist(self) for fmp3 in mp3list: playlist.addMedia(QUrl.fromLocalFile(fmp3)) self.titlePlayer.setPlaylist(playlist) self.titlePlayer.play()
def __init__(self, parent=None): super(MainWindowAction, self).__init__(parent) self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.local_music_path = [] self.setupUi(self) self.init() self.show()
def __init__(self): """Initialize player and load playlist if any.""" super().__init__() self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.player.setPlaylist(self.playlist) self.shuffling = False self.repeatingPlaylist = False self.repeatingSong = False self.musicOrder = [] self.loadPlaylist(QUrl( 'file://{}/lastListened.m3u'.format(os.getcwd()))) self.lyricsApi = 'http://api.musixmatch.com/ws/1.1/' self.lyricsApiKey = '4b364f0652e471aa50813a22cdf830ea' self.lastFMapi = 'http://ws.audioscrobbler.com/2.0/' self.lastFMapikey = '052c43a00a4fc294bb3c9e0c38bdf710' self.lastFMsecret = '14c66392fa9c6c142a41ccc2b0674e19' self.username = None self.password = None self.network = None self.error = 'Something went wrong! Try again later.'
def __init__(self): super().__init__() self._prevSong=0 self._skipped=False self._playlist=QMediaPlaylist(self) self.setPlaylist(self._playlist) self.currentMediaChanged.connect(self.unsetSkipped)
def initUI(self): self.player = QMediaPlayer() self.playlist = QMediaPlaylist() vbox = QVBoxLayout() hbox = QHBoxLayout() self.setGeometry(300, 300, 290, 150) self.slider = QSlider(Qt.Horizontal) self.playBtn = QPushButton('►') self.nextBtn = QPushButton('>') self.prevBtn = QPushButton('<') self.nextBtn.clicked.connect(self.nextSong) self.prevBtn.clicked.connect(self.prevSong) self.playBtn.clicked.connect(self.playSong) self.setWindowTitle('VK music') self.list = QListWidget(self) self.list.currentItemChanged.connect(self.selectSong) for track in self.vk.method('audio.get').get('items'): self.list.addItem(SongWidgetItem(track)) self.playlist.addMedia(QMediaContent(QUrl(track['url']))) hbox.addWidget(self.prevBtn) hbox.addWidget(self.playBtn) hbox.addWidget(self.nextBtn) hbox.addWidget(self.slider) self.player.setPlaylist(self.playlist) self.player.positionChanged.connect(self.setPosition) vbox.addWidget(self.list) vbox.addLayout(hbox) self.setLayout(vbox) self.show()
class MusicList(QListWidget): def __init__(self): super(MusicList, self).__init__() self.__musicList = [] self.setFixedWidth(250) self.setFont(QFont('宋体', 10,)) self.setObjectName('musicList') self.setStyleSheet('#musicList{background-color: rgba(0, 0, 0, 120); color: "green";} #musicList:item{height: 25;}') self.itemDoubleClicked.connect(self.music_double_clicked) # 初始化多媒体播放器和播放列表 self.player = QMediaPlayer() self.playlist = QMediaPlaylist(self.player) self.player.setPlaylist(self.playlist) def add_music_item(self, file_names): for file in file_names: self.addItem(file.split('/')[-1]) self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(file))) def music_double_clicked(self): music_list_index = self.currentRow() self.music_play(music_list_index) def music_play(self, music_list_index): self.playlist.setCurrentIndex(music_list_index) self.player.play() def add_network_music(self, music_name, music_url): print(music_name) self.addItem(music_name) self.playlist.addMedia(QMediaContent(QUrl(music_url)))
def __init__(self): super(MusicList, self).__init__() self.__musicList = [] self.setFixedWidth(250) self.setFont(QFont('宋体', 10,)) self.setObjectName('musicList') self.setStyleSheet('#musicList{background-color: rgba(0, 0, 0, 120); color: "green";} #musicList:item{height: 25;}') self.itemDoubleClicked.connect(self.music_double_clicked) # 初始化多媒体播放器和播放列表 self.player = QMediaPlayer() self.playlist = QMediaPlaylist(self.player) self.player.setPlaylist(self.playlist)
def __init__(self, parent=None): super(DirectoryPlaylist, self).__init__(parent) self._directories_urls = set() self._added_song_urls = set() self._tracks = [] self._qPlaylist = QMediaPlaylist(parent) self._qPlaylist.mediaAboutToBeInserted.connect( lambda s, e: self.mediaAboutToBeInserted.emit(s, e)) self._qPlaylist.mediaInserted.connect( lambda s, e: self.mediaInserted.emit(s, e)) self._qPlaylist.mediaAboutToBeRemoved.connect( lambda s, e: self.mediaAboutToBeRemoved.emit(s, e)) self._qPlaylist.mediaRemoved.connect( lambda s, e: self.mediaRemoved.emit(s, e)) self._qPlaylist.mediaChanged.connect( lambda s, e: self.mediaChanged.emit(s, e))
def __init__(self, playList = [], ddir = "data", parent = None): super(LolitaPlayer, self).__init__(parent) try: # 播放列表 self.playList = QMediaPlaylist(parent) # 设置只播放一次 self.playList.setPlaybackMode(QMediaPlaylist.CurrentItemOnce) # 读取配置文件中的音乐路径 self._playList = playList # 添加到列表里 self.playList.addMedia([QMediaContent(QUrl(item[1].format(DATA_DIR = ddir))) for item in self._playList]) self.playList.setCurrentIndex(0) # 设置播放列表 self.setPlaylist(self.playList) # 设置音量 self.setVolume(100) except Exception as e: traceback.print_exc(e)
class MusicPlayer(QMainWindow): """MusicPlayer houses all of elements that directly interact with the main window.""" def __init__(self, parent=None): """Initialize the QMainWindow widget. The window title, window icon, and window size are initialized here as well as the following widgets: QMediaPlayer, QMediaPlaylist, QMediaContent, QMenuBar, QToolBar, QLabel, QPixmap, QSlider, QDockWidget, QListWidget, QWidget, and QVBoxLayout. The connect signals for relavant widgets are also initialized. """ super(MusicPlayer, self).__init__(parent) self.setWindowTitle('Mosaic') window_icon = utilities.resource_filename('mosaic.images', 'icon.png') self.setWindowIcon(QIcon(window_icon)) self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63) # Initiates Qt objects to be used by MusicPlayer self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.playlist_location = defaults.Settings().playlist_path self.content = QMediaContent() self.menu = self.menuBar() self.toolbar = QToolBar() self.art = QLabel() self.pixmap = QPixmap() self.slider = QSlider(Qt.Horizontal) self.duration_label = QLabel() self.playlist_dock = QDockWidget('Playlist', self) self.library_dock = QDockWidget('Media Library', self) self.playlist_view = QListWidget() self.library_view = library.MediaLibraryView() self.library_model = library.MediaLibraryModel() self.preferences = configuration.PreferencesDialog() self.widget = QWidget() self.layout = QVBoxLayout(self.widget) self.duration = 0 self.playlist_dock_state = None self.library_dock_state = None # Sets QWidget() as the central widget of the main window self.setCentralWidget(self.widget) self.layout.setContentsMargins(0, 0, 0, 0) self.art.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) # Initiates the playlist dock widget and the library dock widget self.addDockWidget(defaults.Settings().dock_position, self.playlist_dock) self.playlist_dock.setWidget(self.playlist_view) self.playlist_dock.setVisible(defaults.Settings().playlist_on_start) self.playlist_dock.setFeatures(QDockWidget.DockWidgetClosable) self.addDockWidget(defaults.Settings().dock_position, self.library_dock) self.library_dock.setWidget(self.library_view) self.library_dock.setVisible(defaults.Settings().media_library_on_start) self.library_dock.setFeatures(QDockWidget.DockWidgetClosable) self.tabifyDockWidget(self.playlist_dock, self.library_dock) # Sets the range of the playback slider and sets the playback mode as looping self.slider.setRange(0, self.player.duration() / 1000) self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) # OSX system menu bar causes conflicts with PyQt5 menu bar if sys.platform == 'darwin': self.menu.setNativeMenuBar(False) # Initiates Settings in the defaults module to give access to settings.toml defaults.Settings() # Signals that connect to other methods when they're called self.player.metaDataChanged.connect(self.display_meta_data) self.slider.sliderMoved.connect(self.seek) self.player.durationChanged.connect(self.song_duration) self.player.positionChanged.connect(self.song_position) self.player.stateChanged.connect(self.set_state) self.playlist_view.itemActivated.connect(self.activate_playlist_item) self.library_view.activated.connect(self.open_media_library) self.playlist.currentIndexChanged.connect(self.change_index) self.playlist.mediaInserted.connect(self.initialize_playlist) self.playlist_dock.visibilityChanged.connect(self.dock_visiblity_change) self.library_dock.visibilityChanged.connect(self.dock_visiblity_change) self.preferences.dialog_media_library.media_library_line.textChanged.connect(self.change_media_library_path) self.preferences.dialog_view_options.dropdown_box.currentIndexChanged.connect(self.change_window_size) self.art.mousePressEvent = self.press_playback # Creating the menu controls, media controls, and window size of the music player self.menu_controls() self.media_controls() self.load_saved_playlist() def menu_controls(self): """Initiate the menu bar and add it to the QMainWindow widget.""" self.file = self.menu.addMenu('File') self.edit = self.menu.addMenu('Edit') self.playback = self.menu.addMenu('Playback') self.view = self.menu.addMenu('View') self.help_ = self.menu.addMenu('Help') self.file_menu() self.edit_menu() self.playback_menu() self.view_menu() self.help_menu() def media_controls(self): """Create the bottom toolbar and controls used for media playback.""" self.addToolBar(Qt.BottomToolBarArea, self.toolbar) self.toolbar.setMovable(False) play_icon = utilities.resource_filename('mosaic.images', 'md_play.png') self.play_action = QAction(QIcon(play_icon), 'Play', self) self.play_action.triggered.connect(self.player.play) stop_icon = utilities.resource_filename('mosaic.images', 'md_stop.png') self.stop_action = QAction(QIcon(stop_icon), 'Stop', self) self.stop_action.triggered.connect(self.player.stop) previous_icon = utilities.resource_filename('mosaic.images', 'md_previous.png') self.previous_action = QAction(QIcon(previous_icon), 'Previous', self) self.previous_action.triggered.connect(self.previous) next_icon = utilities.resource_filename('mosaic.images', 'md_next.png') self.next_action = QAction(QIcon(next_icon), 'Next', self) self.next_action.triggered.connect(self.playlist.next) repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png') self.repeat_action = QAction(QIcon(repeat_icon), 'Repeat', self) self.repeat_action.setShortcut('R') self.repeat_action.triggered.connect(self.repeat_song) self.toolbar.addAction(self.play_action) self.toolbar.addAction(self.stop_action) self.toolbar.addAction(self.previous_action) self.toolbar.addAction(self.next_action) self.toolbar.addAction(self.repeat_action) self.toolbar.addWidget(self.slider) self.toolbar.addWidget(self.duration_label) def file_menu(self): """Add a file menu to the menu bar. The file menu houses the Open File, Open Multiple Files, Open Playlist, Open Directory, and Exit Application menu items. """ self.open_action = QAction('Open File', self) self.open_action.setShortcut('O') self.open_action.triggered.connect(self.open_file) self.open_multiple_files_action = QAction('Open Multiple Files', self) self.open_multiple_files_action.setShortcut('M') self.open_multiple_files_action.triggered.connect(self.open_multiple_files) self.open_playlist_action = QAction('Open Playlist', self) self.open_playlist_action.setShortcut('CTRL+P') self.open_playlist_action.triggered.connect(self.open_playlist) self.open_directory_action = QAction('Open Directory', self) self.open_directory_action.setShortcut('D') self.open_directory_action.triggered.connect(self.open_directory) self.save_playlist_action = QAction('Save Playlist', self) self.save_playlist_action.setShortcut('CTRL+S') self.save_playlist_action.triggered.connect(self.save_playlist) self.exit_action = QAction('Quit', self) self.exit_action.setShortcut('CTRL+Q') self.exit_action.triggered.connect(self.closeEvent) self.file.addAction(self.open_action) self.file.addAction(self.open_multiple_files_action) self.file.addAction(self.open_playlist_action) self.file.addAction(self.open_directory_action) self.file.addSeparator() self.file.addAction(self.save_playlist_action) self.file.addSeparator() self.file.addAction(self.exit_action) def edit_menu(self): """Add an edit menu to the menu bar. The edit menu houses the preferences item that opens a preferences dialog that allows the user to customize features of the music player. """ self.preferences_action = QAction('Preferences', self) self.preferences_action.setShortcut('CTRL+SHIFT+P') self.preferences_action.triggered.connect(lambda: self.preferences.exec_()) self.edit.addAction(self.preferences_action) def playback_menu(self): """Add a playback menu to the menu bar. The playback menu houses """ self.play_playback_action = QAction('Play', self) self.play_playback_action.setShortcut('P') self.play_playback_action.triggered.connect(self.player.play) self.stop_playback_action = QAction('Stop', self) self.stop_playback_action.setShortcut('S') self.stop_playback_action.triggered.connect(self.player.stop) self.previous_playback_action = QAction('Previous', self) self.previous_playback_action.setShortcut('B') self.previous_playback_action.triggered.connect(self.previous) self.next_playback_action = QAction('Next', self) self.next_playback_action.setShortcut('N') self.next_playback_action.triggered.connect(self.playlist.next) self.playback.addAction(self.play_playback_action) self.playback.addAction(self.stop_playback_action) self.playback.addAction(self.previous_playback_action) self.playback.addAction(self.next_playback_action) def view_menu(self): """Add a view menu to the menu bar. The view menu houses the Playlist, Media Library, Minimalist View, and Media Information menu items. The Playlist item toggles the playlist dock into and out of view. The Media Library items toggles the media library dock into and out of view. The Minimalist View item resizes the window and shows only the menu bar and player controls. The Media Information item opens a dialog that shows information relevant to the currently playing song. """ self.dock_action = self.playlist_dock.toggleViewAction() self.dock_action.setShortcut('CTRL+ALT+P') self.library_dock_action = self.library_dock.toggleViewAction() self.library_dock_action.setShortcut('CTRL+ALT+L') self.minimalist_view_action = QAction('Minimalist View', self) self.minimalist_view_action.setShortcut('CTRL+ALT+M') self.minimalist_view_action.setCheckable(True) self.minimalist_view_action.triggered.connect(self.minimalist_view) self.view_media_info_action = QAction('Media Information', self) self.view_media_info_action.setShortcut('CTRL+SHIFT+M') self.view_media_info_action.triggered.connect(self.media_information_dialog) self.view.addAction(self.dock_action) self.view.addAction(self.library_dock_action) self.view.addSeparator() self.view.addAction(self.minimalist_view_action) self.view.addSeparator() self.view.addAction(self.view_media_info_action) def help_menu(self): """Add a help menu to the menu bar. The help menu houses the about dialog that shows the user information related to the application. """ self.about_action = QAction('About', self) self.about_action.setShortcut('H') self.about_action.triggered.connect(lambda: about.AboutDialog().exec_()) self.help_.addAction(self.about_action) def open_file(self): """Open the selected file and add it to a new playlist.""" filename, success = QFileDialog.getOpenFileName(self, 'Open File', '', 'Audio (*.mp3 *.flac)', '', QFileDialog.ReadOnly) if success: file_info = QFileInfo(filename).fileName() playlist_item = QListWidgetItem(file_info) self.playlist.clear() self.playlist_view.clear() self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(filename))) self.player.setPlaylist(self.playlist) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) self.player.play() def open_multiple_files(self): """Open the selected files and add them to a new playlist.""" filenames, success = QFileDialog.getOpenFileNames(self, 'Open Multiple Files', '', 'Audio (*.mp3 *.flac)', '', QFileDialog.ReadOnly) if success: self.playlist.clear() self.playlist_view.clear() for file in natsort.natsorted(filenames, alg=natsort.ns.PATH): file_info = QFileInfo(file).fileName() playlist_item = QListWidgetItem(file_info) self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file))) self.player.setPlaylist(self.playlist) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) self.player.play() def open_playlist(self): """Load an M3U or PLS file into a new playlist.""" playlist, success = QFileDialog.getOpenFileName(self, 'Open Playlist', '', 'Playlist (*.m3u *.pls)', '', QFileDialog.ReadOnly) if success: playlist = QUrl.fromLocalFile(playlist) self.playlist.clear() self.playlist_view.clear() self.playlist.load(playlist) self.player.setPlaylist(self.playlist) for song_index in range(self.playlist.mediaCount()): file_info = self.playlist.media(song_index).canonicalUrl().fileName() playlist_item = QListWidgetItem(file_info) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) self.player.play() def save_playlist(self): """Save the media in the playlist dock as a new M3U playlist.""" playlist, success = QFileDialog.getSaveFileName(self, 'Save Playlist', '', 'Playlist (*.m3u)', '') if success: saved_playlist = "{}.m3u" .format(playlist) self.playlist.save(QUrl().fromLocalFile(saved_playlist), "m3u") def load_saved_playlist(self): """Load the saved playlist if user setting permits.""" saved_playlist = "{}/.m3u" .format(self.playlist_location) if os.path.exists(saved_playlist): playlist = QUrl().fromLocalFile(saved_playlist) self.playlist.load(playlist) self.player.setPlaylist(self.playlist) for song_index in range(self.playlist.mediaCount()): file_info = self.playlist.media(song_index).canonicalUrl().fileName() playlist_item = QListWidgetItem(file_info) playlist_item.setToolTip(file_info) self.playlist_view.addItem(playlist_item) self.playlist_view.setCurrentRow(0) def open_directory(self): """Open the selected directory and add the files within to an empty playlist.""" directory = QFileDialog.getExistingDirectory(self, 'Open Directory', '', QFileDialog.ReadOnly) if directory: self.playlist.clear() self.playlist_view.clear() for dirpath, __, files in os.walk(directory): for filename in natsort.natsorted(files, alg=natsort.ns.PATH): file = os.path.join(dirpath, filename) if filename.endswith(('mp3', 'flac')): self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file))) playlist_item = QListWidgetItem(filename) playlist_item.setToolTip(filename) self.playlist_view.addItem(playlist_item) self.player.setPlaylist(self.playlist) self.playlist_view.setCurrentRow(0) self.player.play() def open_media_library(self, index): """Open a directory or file from the media library into an empty playlist.""" self.playlist.clear() self.playlist_view.clear() if self.library_model.fileName(index).endswith(('mp3', 'flac')): self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(self.library_model.filePath(index)))) self.playlist_view.addItem(self.library_model.fileName(index)) elif self.library_model.isDir(index): directory = self.library_model.filePath(index) for dirpath, __, files in os.walk(directory): for filename in natsort.natsorted(files, alg=natsort.ns.PATH): file = os.path.join(dirpath, filename) if filename.endswith(('mp3', 'flac')): self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file))) playlist_item = QListWidgetItem(filename) playlist_item.setToolTip(filename) self.playlist_view.addItem(playlist_item) self.player.setPlaylist(self.playlist) self.player.play() def display_meta_data(self): """Display the current song's metadata in the main window. If the current song contains metadata, its cover art is extracted and shown in the main window while the track number, artist, album, and track title are shown in the window title. """ if self.player.isMetaDataAvailable(): file_path = self.player.currentMedia().canonicalUrl().toLocalFile() (album, artist, title, track_number, *__, artwork) = metadata.metadata(file_path) try: self.pixmap.loadFromData(artwork) except TypeError: self.pixmap = QPixmap(artwork) meta_data = '{} - {} - {} - {}' .format(track_number, artist, album, title) self.setWindowTitle(meta_data) self.art.setScaledContents(True) self.art.setPixmap(self.pixmap) self.layout.addWidget(self.art) def initialize_playlist(self, start): """Display playlist and reset playback mode when media inserted into playlist.""" if start == 0: if self.library_dock.isVisible(): self.playlist_dock.setVisible(True) self.playlist_dock.show() self.playlist_dock.raise_() if self.playlist.playbackMode() != QMediaPlaylist.Sequential: self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png') self.repeat_action.setIcon(QIcon(repeat_icon)) def press_playback(self, event): """Change the playback of the player on cover art mouse event. When the cover art is clicked, the player will play the media if the player is either paused or stopped. If the media is playing, the media is set to pause. """ if event.button() == 1 and configuration.Playback().cover_art_playback.isChecked(): if (self.player.state() == QMediaPlayer.StoppedState or self.player.state() == QMediaPlayer.PausedState): self.player.play() elif self.player.state() == QMediaPlayer.PlayingState: self.player.pause() def seek(self, seconds): """Set the position of the song to the position dragged to by the user.""" self.player.setPosition(seconds * 1000) def song_duration(self, duration): """Set the slider to the duration of the currently played media.""" duration /= 1000 self.duration = duration self.slider.setMaximum(duration) def song_position(self, progress): """Move the horizontal slider in sync with the duration of the song. The progress is relayed to update_duration() in order to display the time label next to the slider. """ progress /= 1000 if not self.slider.isSliderDown(): self.slider.setValue(progress) self.update_duration(progress) def update_duration(self, current_duration): """Calculate the time played and the length of the song. Both of these times are sent to duration_label() in order to display the times on the toolbar. """ duration = self.duration if current_duration or duration: time_played = QTime((current_duration / 3600) % 60, (current_duration / 60) % 60, (current_duration % 60), (current_duration * 1000) % 1000) song_length = QTime((duration / 3600) % 60, (duration / 60) % 60, (duration % 60), (duration * 1000) % 1000) if duration > 3600: time_format = "hh:mm:ss" else: time_format = "mm:ss" time_display = "{} / {}" .format(time_played.toString(time_format), song_length.toString(time_format)) else: time_display = "" self.duration_label.setText(time_display) def set_state(self, state): """Change the icon in the toolbar in relation to the state of the player. The play icon changes to the pause icon when a song is playing and the pause icon changes back to the play icon when either paused or stopped. """ if self.player.state() == QMediaPlayer.PlayingState: pause_icon = utilities.resource_filename('mosaic.images', 'md_pause.png') self.play_action.setIcon(QIcon(pause_icon)) self.play_action.triggered.connect(self.player.pause) elif (self.player.state() == QMediaPlayer.PausedState or self.player.state() == QMediaPlayer.StoppedState): self.play_action.triggered.connect(self.player.play) play_icon = utilities.resource_filename('mosaic.images', 'md_play.png') self.play_action.setIcon(QIcon(play_icon)) def previous(self): """Move to the previous song in the playlist. Moves to the previous song in the playlist if the current song is less than five seconds in. Otherwise, restarts the current song. """ if self.player.position() <= 5000: self.playlist.previous() else: self.player.setPosition(0) def repeat_song(self): """Set the current media to repeat and change the repeat icon accordingly. There are four playback modes: repeat none, repeat all, repeat once, and shuffle. Clicking the repeat button cycles through each playback mode. """ if self.playlist.playbackMode() == QMediaPlaylist.Sequential: self.playlist.setPlaybackMode(QMediaPlaylist.Loop) repeat_on_icon = utilities.resource_filename('mosaic.images', 'md_repeat_all.png') self.repeat_action.setIcon(QIcon(repeat_on_icon)) elif self.playlist.playbackMode() == QMediaPlaylist.Loop: self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop) repeat_on_icon = utilities.resource_filename('mosaic.images', 'md_repeat_once.png') self.repeat_action.setIcon(QIcon(repeat_on_icon)) elif self.playlist.playbackMode() == QMediaPlaylist.CurrentItemInLoop: self.playlist.setPlaybackMode(QMediaPlaylist.Random) repeat_icon = utilities.resource_filename('mosaic.images', 'md_shuffle.png') self.repeat_action.setIcon(QIcon(repeat_icon)) elif self.playlist.playbackMode() == QMediaPlaylist.Random: self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png') self.repeat_action.setIcon(QIcon(repeat_icon)) def activate_playlist_item(self, item): """Set the active media to the playlist item dobule-clicked on by the user.""" current_index = self.playlist_view.row(item) if self.playlist.currentIndex() != current_index: self.playlist.setCurrentIndex(current_index) if self.player.state() != QMediaPlayer.PlayingState: self.player.play() def change_index(self, row): """Highlight the row in the playlist of the active media.""" self.playlist_view.setCurrentRow(row) def minimalist_view(self): """Resize the window to only show the menu bar and audio controls.""" if self.minimalist_view_action.isChecked(): if self.playlist_dock.isVisible(): self.playlist_dock_state = True if self.library_dock.isVisible(): self.library_dock_state = True self.library_dock.close() self.playlist_dock.close() QTimer.singleShot(10, lambda: self.resize(500, 0)) else: self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63) if self.library_dock_state: self.library_dock.setVisible(True) if self.playlist_dock_state: self.playlist_dock.setVisible(True) def dock_visiblity_change(self, visible): """Change the size of the main window when the docks are toggled.""" if visible and self.playlist_dock.isVisible() and not self.library_dock.isVisible(): self.resize(defaults.Settings().window_size + self.playlist_dock.width() + 6, self.height()) elif visible and not self.playlist_dock.isVisible() and self.library_dock.isVisible(): self.resize(defaults.Settings().window_size + self.library_dock.width() + 6, self.height()) elif visible and self.playlist_dock.isVisible() and self.library_dock.isVisible(): self.resize(defaults.Settings().window_size + self.library_dock.width() + 6, self.height()) elif (not visible and not self.playlist_dock.isVisible() and not self.library_dock.isVisible()): self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63) def media_information_dialog(self): """Show a dialog of the current song's metadata.""" if self.player.isMetaDataAvailable(): file_path = self.player.currentMedia().canonicalUrl().toLocalFile() else: file_path = None dialog = information.InformationDialog(file_path) dialog.exec_() def change_window_size(self): """Change the window size of the music player.""" self.playlist_dock.close() self.library_dock.close() self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63) def change_media_library_path(self, path): """Change the media library path to the new path selected in the preferences dialog.""" self.library_model.setRootPath(path) self.library_view.setModel(self.library_model) self.library_view.setRootIndex(self.library_model.index(path)) def closeEvent(self, event): """Override the PyQt close event in order to handle save playlist on close.""" playlist = "{}/.m3u" .format(self.playlist_location) if defaults.Settings().save_playlist_on_close: self.playlist.save(QUrl().fromLocalFile(playlist), "m3u") else: if os.path.exists(playlist): os.remove(playlist) QApplication.quit()
class Window(QtWidgets.QDialog): def __init__(self): super().__init__() self.setGeometry(50, 50, 300, 400) self.setWindowTitle("Rolev Player") # LIBRARY ROOT DIR FOLDER self.search_label = QtWidgets.QLabel("Select a music folder:", self) self.search_label.setGeometry(10, 5, 205, 10) self.btn_root_folder = QtWidgets.QPushButton("Browse", self) self.btn_root_folder.setGeometry(215, 20, 75, 25) # the text field of the currently selected root directory self.dir_text_field = QtWidgets.QLineEdit(self) self.dir_text_field.setGeometry(10, 20, 200, 25) self.btn_root_folder.clicked.connect(self.on_btn_root_folder) # CURRENT MEDIA LABEL self.current_media_label = QtWidgets.QLabel("Now Playing: ", self) self.current_media_label.setGeometry(10, 260, 250, 15) # CURRENT ALBUM COVER self.current_album_cover = QtWidgets.QLabel("Image", self) self.current_album_cover.setGeometry(10, 180, 75, 75) self.current_album_cover.setScaledContents(True) # ARTIST DROP BOX self.artist_select_label = QtWidgets.QLabel("Artist", self) self.artist_select_label.setGeometry(10, 50, 250, 25) self.artist_select = QtWidgets.QComboBox(self) self.artist_select.setGeometry(10, 70, 250, 25) self.artist_select.activated[str].connect(self.on_artist_selection) # ALBUMS DROP BOX self.album_select_label = QtWidgets.QLabel("Albums", self) self.album_select_label.setGeometry(10, 90, 250, 25) self.album_select = QtWidgets.QComboBox(self) self.album_select.setGeometry(10, 110, 250, 25) self.album_select.activated[str].connect(self.on_album_selection) # SONGS DROP BOX self.song_select_label = QtWidgets.QLabel("Current Playlist", self) self.song_select_label.setGeometry(10, 130, 250, 25) self.song_select = QtWidgets.QComboBox(self) self.song_select.setGeometry(10, 150, 250, 25) self.song_select.activated[str].connect(self.on_song_selection) # PLAYLIST self.playlist = QMediaPlaylist() self.playlist.currentIndexChanged.connect(self.meta_data_changed) # MEDIA PLAYER self.player = QMediaPlayer() self.player.setPlaylist(self.playlist) self.player.playlist().setPlaybackMode(QMediaPlaylist.Loop) self.player.setVolume(50) self.player.durationChanged.connect(self.on_dur_change) self.player.positionChanged.connect(self.on_pos_change) # VOLUME SLIDER self.slider_volume_label = QtWidgets.QLabel("Volume", self) self.slider_volume_label.setGeometry(10, 345, 50, 25) self.slider_volume = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.slider_volume.setGeometry(60, 350, 130, 20) self.slider_volume.setRange(0, 100) self.slider_volume.setValue(50) self.slider_volume.valueChanged.connect(self.volume_change) # PROGRESS SLIDER self.slider_progress_label = QtWidgets.QLabel("Progress", self) self.slider_progress_label.setGeometry(10, 315, 50, 25) self.slider_progress = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.slider_progress.setGeometry(60, 320, 130, 20) self.slider_progress.sliderMoved.connect(self.progress_change) # LYRICS SEARCH self.btn_lyrics = QtWidgets.QPushButton("Search\n Lyrics", self) self.btn_lyrics.setGeometry(220, 310, 70, 80) self.btn_lyrics.clicked.connect(self.on_lyrics) # ALBUM INFO SEARCH self.btn_album_info = QtWidgets.QPushButton( "Search\nAlbum\nInfo", self) self.btn_album_info.setGeometry(105, 180, 75, 75) self.btn_album_info.clicked.connect(self.on_album_info) # ARTIST INFO SEARCH self.btn_artist_info = QtWidgets.QPushButton( "Search\nArtist\nInfo", self) self.btn_artist_info.setGeometry(200, 180, 75, 75) self.btn_artist_info.clicked.connect(self.on_artist_info) # PREV SONG BUTTON self.btn_prev = QtWidgets.QPushButton("Prev", self) self.btn_prev.setGeometry(10, 280, 75, 25) self.btn_prev.clicked.connect(self.on_btn_prev) # NEXT SONG BUTTON self.btn_next = QtWidgets.QPushButton("Next", self) self.btn_next.setGeometry(200, 280, 75, 25) self.btn_next.clicked.connect(self.on_btn_next) # PLAY/PAUSE BUTTON self.btn_play_pause = QtWidgets.QPushButton("Play", self) self.btn_play_pause.setGeometry(105, 280, 75, 30) self.btn_play_pause.clicked.connect(self.on_btn_play_pause) self.show() def on_btn_root_folder(self): self.root_dir = QtWidgets.QFileDialog().getExistingDirectory() self.dir_text_field.setText(self.root_dir) self.library = LibraryLoader.load_music_from_dir( self.dir_text_field.text()) self.artist_select.clear() self.album_select.clear() self.song_select.clear() self.playlist.clear() self.btn_play_pause.setText("Play") self.artist_select.addItem("All Artists") for artist in self.library: self.artist_select.addItem(artist) for album in self.library[artist]: self.album_select.addItem(album) self.load_all_songs() def on_artist_selection(self): current_artist = self.artist_select.currentText() self.album_select.clear() self.song_select.clear() self.playlist.clear() self.btn_play_pause.setText("Play") self.album_select.addItem("All Albums") if current_artist == "All Artists": for artist in self.library: for album in self.library[artist]: self.album_select.addItem(album) self.load_all_songs() else: for album in self.library[current_artist]: self.album_select.addItem(album) self.load_all_from_artist(current_artist) def load_all_songs(self): for artist in self.library: for album in self.library[artist]: for song in self.library[artist][album]: self.song_select.addItem(song[0]) self.playlist.addMedia( QMediaContent(QtCore.QUrl.fromLocalFile(song[1]))) def load_all_from_artist(self, artist): for album in self.library[artist]: for song in self.library[artist][album]: self.song_select.addItem(song[0]) self.playlist.addMedia( QMediaContent(QtCore.QUrl.fromLocalFile(song[1]))) def on_album_selection(self): current_artist = self.artist_select.currentText() current_album = self.album_select.currentText() self.song_select.clear() self.playlist.clear() self.btn_play_pause.setText("Play") if current_album == "All Albums" and current_artist == "All Artists": self.load_all_songs() elif current_album == "All Albums": self.load_all_from_artist(current_artist) elif current_artist == "All Artists": for artist in self.library: for album in self.library[artist]: if album == self.album_select.currentText(): for song in self.library[artist][album]: self.song_select.addItem(song[0]) self.playlist.addMedia( QMediaContent( QtCore.QUrl.fromLocalFile(song[1]))) else: for song in self.library[current_artist][current_album]: self.song_select.addItem(song[0]) self.playlist.addMedia( QMediaContent(QtCore.QUrl.fromLocalFile(song[1]))) def on_song_selection(self): index = self.song_select.currentIndex() self.playlist.setCurrentIndex(index) # GETTING THE CURRENT SONG METADATA # Returns a SONG OBJECT and not the current song title # For the title of the currently playing song use get_current_title() def get_current_song(self): curr_url = self.playlist.currentMedia().canonicalUrl().toString()[8:] if curr_url: return LibraryLoader.create_song(curr_url) def get_current_artist(self): if self.get_current_song() is not None: return self.get_current_song().artist def get_current_album(self): if self.get_current_song() is not None: return self.get_current_song().album def get_current_path(self): if self.get_current_song() is not None: return self.get_current_song().path def get_current_album_path(self): if self.get_current_path() is not None: return self.get_current_path().rsplit("/", 1)[0] def get_current_title(self): if self.get_current_song() is not None: return self.get_current_song().name def on_lyrics(self): if self.get_current_song() is not None: curr_artist = self.get_current_artist() curr_song = self.get_current_title() found_lyrics = RequestLyrics.search_song_lyrics( curr_artist, curr_song) choice = QtWidgets.QMessageBox.question( self, "Lyrics", found_lyrics[0], QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No) if choice == QtWidgets.QMessageBox.Yes: webbrowser.open(found_lyrics[1]) else: QtWidgets.QMessageBox.information( self, "Lyrics", "No lyrics found or no media is loaded!") def on_album_info(self): album = self.get_current_album() artist = self.get_current_artist() if (album is None) or (artist is None): print("Please, load a song first!") else: artist_info, album_info = AlbumArtwork.album_artist_info( artist, album) if album_info is not None: webbrowser.open(album_info) def on_artist_info(self): album = self.get_current_album() artist = self.get_current_artist() if (album is None) or (artist is None): print("Please, load a song first!") else: artist_info, album_info = AlbumArtwork.album_artist_info( artist, album) if artist_info is not None: webbrowser.open(artist_info) def on_btn_play_pause(self): if self.player.state() in (0, 2): self.player.play() if self.player.state() == 1: self.btn_play_pause.setText("Pause") else: self.player.pause() self.btn_play_pause.setText("Play") def on_btn_next(self): self.player.playlist().next() def on_btn_prev(self): self.player.playlist().previous() def on_dur_change(self, length): self.slider_progress.setMaximum(length) def on_pos_change(self, position): self.slider_progress.setValue(position) def volume_change(self): volume = self.slider_volume.value() self.player.setVolume(volume) def progress_change(self): position = self.slider_progress.value() self.player.setPosition(position) def meta_data_changed(self): now_playing = self.get_current_title() self.current_media_label.setText("Now Playing: " + now_playing) # Updating the currently playing album cover curr_album_path = self.get_current_album_path() curr_album = self.get_current_album() curr_artist = self.get_current_artist() cover_url = AlbumArtwork.album_cover( curr_album_path, curr_artist, curr_album) self.current_album_cover.setPixmap(QPixmap(cover_url)) Scrobbler.scrobble(self.get_current_artist(), self.get_current_title())
class PlaylistWrapper: def __init__(self, name): self.name = name self.songs = [] self.playlist = QMediaPlaylist() def path_to_song(self, song_path): filepath, song_name = os.path.split(song_path) os.chdir(filepath) audio = MP3(song_name) try: title = audio["TIT2"] artist = audio["TPE1"] album = audio["TALB"] except KeyError: title = artist = album = "Unknown" length = audio.info.length return Song(title, artist, album, length, song_path) def add_song(self, song_path): if song_path.split(".")[-1] not in ["mp3", "flac", "ogg"]: raise AssertionError song = self.path_to_song(song_path) filepath = song.path fileInfo = QFileInfo(filepath) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) if fileInfo.suffix().lower() == "mp3" or "flac" or "ogg": self.playlist.addMedia(QMediaContent(url)) self.songs.append(song) def save(self, file_path): os.chdir(file_path) file = open(self.name + ".ltmp", "w") file.write(json.dumps(self.hash_playlist())) file.close() def load(self, file_path): dir_name, file_name = os.path.split(file_path) os.chdir(dir_name) name_parts = file_name.split(".") if not name_parts[-1] == "ltmp": raise AssertionError with open(file_name, "r") as json_file: data = json.load(json_file) for song in data["songs"]: self.add_song(song["path"]) def hash_songs(self): hashed_songs = [] for song in self.songs: hashed_songs.append(song.hash_song()) return hashed_songs def hash_playlist(self): hash_playlist = {} hash_playlist["name"] = self.name hash_playlist["songs"] = self.hash_songs() return hash_playlist def is_empty(self): return len(self.songs) == 0
def __init__(self, name): self.name = name self.songs = [] self.playlist = QMediaPlaylist()
class VKwindow(QWidget): def __init__(self, vkapi): super().__init__() self.vk = vkapi self.initUI() def initUI(self): self.player = QMediaPlayer() self.playlist = QMediaPlaylist() vbox = QVBoxLayout() hbox = QHBoxLayout() self.setGeometry(300, 300, 290, 150) self.slider = QSlider(Qt.Horizontal) self.playBtn = QPushButton('►') self.nextBtn = QPushButton('>') self.prevBtn = QPushButton('<') self.nextBtn.clicked.connect(self.nextSong) self.prevBtn.clicked.connect(self.prevSong) self.playBtn.clicked.connect(self.playSong) self.setWindowTitle('VK music') self.list = QListWidget(self) self.list.currentItemChanged.connect(self.selectSong) for track in self.vk.method('audio.get').get('items'): self.list.addItem(SongWidgetItem(track)) self.playlist.addMedia(QMediaContent(QUrl(track['url']))) hbox.addWidget(self.prevBtn) hbox.addWidget(self.playBtn) hbox.addWidget(self.nextBtn) hbox.addWidget(self.slider) self.player.setPlaylist(self.playlist) self.player.positionChanged.connect(self.setPosition) vbox.addWidget(self.list) vbox.addLayout(hbox) self.setLayout(vbox) self.show() def selectSong(self, curr, prev): self.currentTrack = curr print(curr.getArtist()) def playSong(self): print(self.currentTrack.getArtist()) print(self.list.currentRow()) if self.player.state() == QMediaPlayer.PlayingState and self.list.currentRow() == self.playlist.currentIndex(): self.player.pause() return elif self.player.state() == QMediaPlayer.PausedState: self.player.play() return self.playlist.setCurrentIndex(self.list.currentRow()) self.slider.setTickInterval(self.player.duration()) self.player.play() def setPosition(self, pos): print(pos) self.slider.setTickPosition(pos) def nextSong(self): tmp = self.list.currentRow() size = self.list.count() tmp = (tmp + 1) % size self.list.setCurrentRow(tmp) self.playlist.setCurrentIndex(tmp) self.player.play() def prevSong(self): tmp = self.list.currentRow() size = self.list.count() tmp = (tmp - 1) % size self.list.setCurrentRow(tmp) self.playlist.setCurrentIndex(tmp) self.player.play()
def __init__(self): global playerStarted global wavFileName, fig, chartFig global playerStarted, durationFlag, duration global colorName, text_, counterClick global startAnnotation, endTimeToPlay QtWidgets.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.main_widget = QtWidgets.QWidget(self) playerStarted = False #DEFINE PLAYER-PLAYLIST #---------------------- self.source = QtCore.QUrl.fromLocalFile(os.path.abspath(wavFileName)) self.content = QMediaContent(self.source) self.player = QMediaPlayer() self.playlist = QMediaPlaylist(self) self.playlist.addMedia(self.content) self.player.setPlaylist(self.playlist) # >> Define annotations and gantt chart #---------------------- self.wave = Waveform() fig = self.wave self.chart = Chart() chartFig = self.chart # >> Define player buttons #---------------------- playButton = QPushButton("Play") pauseButton = QPushButton("Pause") stopButton = QPushButton("Stop") # >> Define layouts #---------------------- waveLayout = QVBoxLayout() waveLayout.addWidget(self.wave) waveLayout.addWidget(self.chart) line = QFrame() line.setFrameShape(QFrame.VLine) line.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Expanding) waveLayout.addWidget(line) #Buttons layout buttonLayout = QVBoxLayout() buttonLayout.addWidget(playButton) buttonLayout.addWidget(pauseButton) buttonLayout.addWidget(stopButton) buttonLayout.setAlignment(Qt.AlignTop) # >> Specify final layout align #---------------------- layout = QHBoxLayout(self.main_widget) layout.addLayout(waveLayout) layout.addLayout(buttonLayout) # >> Define buttons connections #---------------------- playButton.clicked.connect(self.Play) pauseButton.clicked.connect(self.Pause) stopButton.clicked.connect(self.Stop) self.main_widget.setFocus() self.setCentralWidget(self.main_widget)
def __init__(self, playlist, parent=None, add_button = None): super(Player, self).__init__(parent) self.add_button = add_button self.colorDialog = None self.trackInfo = "" self.statusInfo = "" self.duration = 0 self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.player.setPlaylist(self.playlist) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.metaDataChanged.connect(self.metaDataChanged) self.playlist.currentIndexChanged.connect(self.playlistPositionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.bufferStatusChanged.connect(self.bufferingProgress) self.player.error.connect(self.displayErrorMessage) self.videoWidget = VideoWidget() self.player.setVideoOutput(self.videoWidget) self.playlistModel = PlaylistModel() self.playlistModel.setPlaylist(self.playlist) self.playlistView = QListView() self.playlistView.setModel(self.playlistModel) self.playlistView.setCurrentIndex( self.playlistModel.index(self.playlist.currentIndex(), 0)) self.playlistView.activated.connect(self.jump) self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, self.player.duration() / 1000) self.labelDuration = QLabel() self.slider.sliderMoved.connect(self.seek) openButton = QPushButton("Open Audio/Video File", clicked=self.open) controls = PlayerControls() controls.setState(self.player.state()) controls.setVolume(self.player.volume()) controls.setMuted(controls.isMuted()) controls.play.connect(self.player.play) controls.pause.connect(self.player.pause) controls.stop.connect(self.player.stop) controls.next.connect(self.playlist.next) controls.previous.connect(self.previousClicked) controls.changeVolume.connect(self.player.setVolume) controls.changeMuting.connect(self.player.setMuted) controls.changeRate.connect(self.player.setPlaybackRate) controls.stop.connect(self.videoWidget.update) self.player.stateChanged.connect(controls.setState) self.player.volumeChanged.connect(controls.setVolume) self.player.mutedChanged.connect(controls.setMuted) displayLayout = QHBoxLayout() displayLayout.addWidget(self.videoWidget, 2) displayLayout.addWidget(self.playlistView) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(openButton) # button to add decoder if add_button: add_decoder_btn = QPushButton("Decode Keystrokes of Selected Media") add_decoder_btn.clicked.connect(add_button) controlLayout.addWidget(add_decoder_btn) # controlLayout.addStretch(1) controlLayout.addWidget(controls) layout = QVBoxLayout() layout.addLayout(displayLayout) hLayout = QHBoxLayout() hLayout.addWidget(self.slider) hLayout.addWidget(self.labelDuration) layout.addLayout(hLayout) layout.addLayout(controlLayout) self.setLayout(layout) if not self.player.isAvailable(): QMessageBox.warning(self, "Service not available", "The QMediaPlayer object does not have a valid service.\n" "Please check the media service plugins are installed.") controls.setEnabled(False) self.playlistView.setEnabled(False) openButton.setEnabled(False) self.metaDataChanged() self.addToPlaylist(playlist)
class DPlayerCore(QWidget): def __init__(self): """Initialize player and load playlist if any.""" super().__init__() self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.player.setPlaylist(self.playlist) self.shuffling = False self.repeatingPlaylist = False self.repeatingSong = False self.musicOrder = [] self.loadPlaylist(QUrl( 'file://{}/lastListened.m3u'.format(os.getcwd()))) self.lyricsApi = 'http://api.musixmatch.com/ws/1.1/' self.lyricsApiKey = '4b364f0652e471aa50813a22cdf830ea' self.lastFMapi = 'http://ws.audioscrobbler.com/2.0/' self.lastFMapikey = '052c43a00a4fc294bb3c9e0c38bdf710' self.lastFMsecret = '14c66392fa9c6c142a41ccc2b0674e19' self.username = None self.password = None self.network = None self.error = 'Something went wrong! Try again later.' def play(self): """Start the player.""" self.player.play() def pause(self): """Pause the player.""" self.player.pause() def stop(self): """Stop the player.""" self.player.stop() def previous(self): """Play previous song.""" self.playlist.previous() def next(self): """Play next song.""" self.playlist.next() def mute(self): """Mute the player.""" self.player.setMuted(True) def unmute(self): """Unmute the player.""" self.player.setMuted(False) def setVolume(self, value): """Set player's volume to value.""" self.player.setVolume(value) def add(self, fileNames): """Add fileNames to the playlist.""" for name in fileNames: url = QUrl.fromLocalFile(QFileInfo(name).absoluteFilePath()) self.playlist.addMedia(QMediaContent(url)) self.musicOrder.append([name]) self.added(len(fileNames)) def added(self, added): """Saves music info in musicOrder.""" for name, index in zip( self.musicOrder[self.playlist.mediaCount() - added:], range(self.playlist.mediaCount() - added, len(self.musicOrder))): name = name[0] artist = self.getArtist(name)[0] title = self.getTitle(name)[0] album = self.getAlbum(name)[0] seconds = self.getDuration(name) duration = QTime(0, seconds // 60, seconds % 60) duration = duration.toString('mm:ss') self.musicOrder[index].extend( [artist, title, album, duration]) def remove(self, songIndexes): """Remove songIndexes from the playlist.""" for index in songIndexes: self.songChanged = True del self.musicOrder[index] self.playlist.removeMedia(index) self.songChanged = False def savePlaylist(self, path): """Save playlist to path.""" if path.toString()[len(path.toString()) - 4:] != '.m3u': path = QUrl('{}.m3u'.format(path.toString())) self.playlist.save(path, 'm3u') def loadPlaylist(self, path): """Load playlist form path.""" count = self.playlist.mediaCount() self.playlist.load(path) for index in range(count, self.playlist.mediaCount()): self.musicOrder.append( [self.playlist.media(index).canonicalUrl().path()]) self.added(self.playlist.mediaCount() - count) def clearPlaylist(self): """Delete all songs in the playlist.""" self.playlist.clear() self.musicOrder = [] def shuffle(self, value): """Shuffle playlist if value = True.""" self.shuffling = value if self.repeatingSong: return if self.shuffling: self.playlist.setPlaybackMode(QMediaPlaylist.Random) elif self.repeatingPlaylist: self.playlist.setPlaybackMode(QMediaPlaylist.Loop) else: self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) def repeatPlaylist(self, value): """Repeat playlist after the last song is finished if value = True.""" self.repeatingPlaylist = value if self.repeatingSong or self.shuffling: return if self.repeatingPlaylist: self.playlist.setPlaybackMode(QMediaPlaylist.Loop) else: self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) def repeatSong(self, value): """Repeat current song if value = True.""" self.repeatingSong = value if self.repeatingSong: self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop) elif self.shuffling: self.playlist.setPlaybackMode(QMediaPlaylist.Random) elif self.repeatingPlaylist: self.playlist.setPlaybackMode(QMediaPlaylist.Loop) else: self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) def sort(self, column, order): """Sort playlist by column in order.""" ordered = sorted(self.musicOrder, key=itemgetter(column + 1), reverse=order) self.clearPlaylist() for song in ordered: url = QUrl.fromLocalFile(QFileInfo(song[0]).absoluteFilePath()) self.playlist.addMedia(QMediaContent(url)) self.musicOrder = ordered def findLyrics(self, index): """Returns lyrics for song at index.""" if self.musicOrder[index][2] == 'Unknown': return 'Unknown song.' searchSong = '{}track.search?q_track={}'.format( self.lyricsApi, self.musicOrder[index][2].replace(' ', '%20')) if self.musicOrder[index][1] != 'Unknown': searchSong = '{}&q_artist={}'.format( searchSong, self.musicOrder[index][1].replace(' ', '%20')) searchSong = '{}&f_has_lyrics=1&apikey={}'.format( searchSong, self.lyricsApiKey) try: requestSong = requests.get(searchSong) except requests.ConnectionError: return self.error songJson = requestSong.json() if requestSong.status_code != 200 or \ songJson['message']['header']['available'] == 0: return self.error songId = songJson[ 'message']['body']['track_list'][0]["track"]["track_id"] searchLyrics = '{}track.lyrics.get?track_id={}&apikey={}'.format( self.lyricsApi, songId, self.lyricsApiKey) try: requestLyrics = requests.get(searchLyrics) except requests.ConnectionError: return self.error if requestLyrics.status_code != 200 or \ songJson['message']['header']['available'] == 0: return self.error return requestLyrics.json()[ 'message']['body']['lyrics']['lyrics_body'][:-58] # spam and bacon def findInfo(self, index): """Returns info about artist and album for index if any.""" info = [] if self.musicOrder[index][1] != 'Unknown': artist = self.artistInfo(self.musicOrder[index][1]) if artist != self.error: info += artist if self.musicOrder[index][1] != 'Unknown' and \ self.musicOrder[index][3] != 'Unknown': album = self.albumInfo(self.musicOrder[index][1], self.musicOrder[index][3]) if album != self.error: info += album if info: return info else: return ['Unknown artist and song!'] def artistInfo(self, artist): """Returns info about artist if any.""" try: response = requests.get( ('{}/?method=artist.getinfo&artist={}&api_key={}&' 'format=json&autocorrect=1').format( self.lastFMapi, artist, self.lastFMapikey)) except Exception: return self.error if response.status_code != 200: return self.error artist = 'Artist: {}'.format(response.json()['artist']['name']) bio = 'Bio: {}'.format( response.json()['artist']['bio']['summary'].replace('.', '.\n')) spam = bio.find('<a') bio = bio[:spam] return [artist, bio] def albumInfo(self, artist, album): """Returns info about album if any.""" try: response = requests.get( ('{}/?method=album.getinfo&artist={}&album={}&api_key={}&' 'format=json&autocorrect=1').format( self.lastFMapi, artist, album, self.lastFMapikey)) except Exception: return self.error if response.status_code != 200 or \ 'album' not in response.json().keys(): return self.error album = 'Album: {}'.format(response.json()['album']['name']) tracks = ['Tracks: '] t = response.json()['album']['tracks']['track'] for track, index in zip(t, range(len(t))): tracks.append('{}. {}'.format(index + 1, track['name'])) info = [album, '\n'.join(tracks)] if 'wiki' in response.json()['album'].keys(): wiki = response.json()['album']['wiki'] if 'published' in wiki.keys(): info.append('Published: {}'.format(wiki['published'])) if 'summary' in wiki.keys(): summary = wiki['summary'].replace('.', '.\n') spam = summary.find('<a') info.append('Summary: {}'.format(summary[:spam])) if 'Musical style' in wiki.keys(): info.append('Musical style: {}'.format(wiki['Musical style'])) return info def login(self, username, password): """Creates lastFM network.""" self.username = username self.password = pylast.md5(password) try: self.network = pylast.LastFMNetwork(api_key=self.lastFMapikey, api_secret=self.lastFMsecret, username=self.username, password_hash=self.password) except Exception: self.username = None self.password = None self.network = None return False return True def logout(self): """Destoys lastFM network and current user info.""" self.username = None self.password = None self.network = None def loveTrack(self, index): """Love track at index in lastFM.""" if self.network is None: return False track = self.network.get_track(self.musicOrder[index][1], self.musicOrder[index][2]) try: track.love() except Exception: return False return True def unloveTrack(self, index): """Unlove track at index in lastFM.""" if self.network is None: return False track = self.network.get_track(self.musicOrder[index][1], self.musicOrder[index][2]) try: track.unlove() except Exception: return False return True def isMuted(self): """Returns True if player is muted.""" return self.player.isMuted() def getArtist(self, song): """Returns the artist of song.""" if song[-4:] == '.mp3': obj = EasyID3(song) if 'artist' in obj.keys(): return obj['artist'] elif 'TAG' in mediainfo(song).keys(): obj = mediainfo(song)['TAG'] if 'artist' in obj.keys(): return [obj['artist']] elif 'ARTIST' in obj.keys(): return [obj['ARTIST']] else: return ['Unknown'] else: return ['Unknown'] def getTitle(self, song): """Returns the title of song.""" if song[-4:] == '.mp3': obj = EasyID3(song) if 'title' in obj.keys(): return obj['title'] elif 'TAG' in mediainfo(song).keys(): obj = mediainfo(song)['TAG'] if 'title' in obj.keys(): return [obj['title']] elif 'TITLE' in obj.keys(): return [obj['TITLE']] else: return ['Unknown'] else: return ['Unknown'] def getAlbum(self, song): """Returns the album of song.""" if song[-4:] == '.mp3': obj = EasyID3(song) if 'album' in obj.keys(): return obj['album'] elif 'TAG' in mediainfo(song).keys(): obj = mediainfo(song)['TAG'] if 'album' in obj.keys(): return [obj['album']] elif 'ALBUM' in obj.keys(): return [obj['ALBUM']] else: return ['Unknown'] else: return ['Unknown'] def getDuration(self, song): """Returns the duration of song.""" if song[-4:] == '.mp3': return MP3(song).info.length return int(float(mediainfo(song)['duration']))
def __init__(self): super().__init__() self.setGeometry(50, 50, 300, 400) self.setWindowTitle("Rolev Player") # LIBRARY ROOT DIR FOLDER self.search_label = QtWidgets.QLabel("Select a music folder:", self) self.search_label.setGeometry(10, 5, 205, 10) self.btn_root_folder = QtWidgets.QPushButton("Browse", self) self.btn_root_folder.setGeometry(215, 20, 75, 25) # the text field of the currently selected root directory self.dir_text_field = QtWidgets.QLineEdit(self) self.dir_text_field.setGeometry(10, 20, 200, 25) self.btn_root_folder.clicked.connect(self.on_btn_root_folder) # CURRENT MEDIA LABEL self.current_media_label = QtWidgets.QLabel("Now Playing: ", self) self.current_media_label.setGeometry(10, 260, 250, 15) # CURRENT ALBUM COVER self.current_album_cover = QtWidgets.QLabel("Image", self) self.current_album_cover.setGeometry(10, 180, 75, 75) self.current_album_cover.setScaledContents(True) # ARTIST DROP BOX self.artist_select_label = QtWidgets.QLabel("Artist", self) self.artist_select_label.setGeometry(10, 50, 250, 25) self.artist_select = QtWidgets.QComboBox(self) self.artist_select.setGeometry(10, 70, 250, 25) self.artist_select.activated[str].connect(self.on_artist_selection) # ALBUMS DROP BOX self.album_select_label = QtWidgets.QLabel("Albums", self) self.album_select_label.setGeometry(10, 90, 250, 25) self.album_select = QtWidgets.QComboBox(self) self.album_select.setGeometry(10, 110, 250, 25) self.album_select.activated[str].connect(self.on_album_selection) # SONGS DROP BOX self.song_select_label = QtWidgets.QLabel("Current Playlist", self) self.song_select_label.setGeometry(10, 130, 250, 25) self.song_select = QtWidgets.QComboBox(self) self.song_select.setGeometry(10, 150, 250, 25) self.song_select.activated[str].connect(self.on_song_selection) # PLAYLIST self.playlist = QMediaPlaylist() self.playlist.currentIndexChanged.connect(self.meta_data_changed) # MEDIA PLAYER self.player = QMediaPlayer() self.player.setPlaylist(self.playlist) self.player.playlist().setPlaybackMode(QMediaPlaylist.Loop) self.player.setVolume(50) self.player.durationChanged.connect(self.on_dur_change) self.player.positionChanged.connect(self.on_pos_change) # VOLUME SLIDER self.slider_volume_label = QtWidgets.QLabel("Volume", self) self.slider_volume_label.setGeometry(10, 345, 50, 25) self.slider_volume = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.slider_volume.setGeometry(60, 350, 130, 20) self.slider_volume.setRange(0, 100) self.slider_volume.setValue(50) self.slider_volume.valueChanged.connect(self.volume_change) # PROGRESS SLIDER self.slider_progress_label = QtWidgets.QLabel("Progress", self) self.slider_progress_label.setGeometry(10, 315, 50, 25) self.slider_progress = QtWidgets.QSlider(QtCore.Qt.Horizontal, self) self.slider_progress.setGeometry(60, 320, 130, 20) self.slider_progress.sliderMoved.connect(self.progress_change) # LYRICS SEARCH self.btn_lyrics = QtWidgets.QPushButton("Search\n Lyrics", self) self.btn_lyrics.setGeometry(220, 310, 70, 80) self.btn_lyrics.clicked.connect(self.on_lyrics) # ALBUM INFO SEARCH self.btn_album_info = QtWidgets.QPushButton( "Search\nAlbum\nInfo", self) self.btn_album_info.setGeometry(105, 180, 75, 75) self.btn_album_info.clicked.connect(self.on_album_info) # ARTIST INFO SEARCH self.btn_artist_info = QtWidgets.QPushButton( "Search\nArtist\nInfo", self) self.btn_artist_info.setGeometry(200, 180, 75, 75) self.btn_artist_info.clicked.connect(self.on_artist_info) # PREV SONG BUTTON self.btn_prev = QtWidgets.QPushButton("Prev", self) self.btn_prev.setGeometry(10, 280, 75, 25) self.btn_prev.clicked.connect(self.on_btn_prev) # NEXT SONG BUTTON self.btn_next = QtWidgets.QPushButton("Next", self) self.btn_next.setGeometry(200, 280, 75, 25) self.btn_next.clicked.connect(self.on_btn_next) # PLAY/PAUSE BUTTON self.btn_play_pause = QtWidgets.QPushButton("Play", self) self.btn_play_pause.setGeometry(105, 280, 75, 30) self.btn_play_pause.clicked.connect(self.on_btn_play_pause) self.show()
def __init__(self): super(VideoPlayer, self).__init__() self._player = QMediaPlayer() self._playlist = QMediaPlaylist() self._stopped = True
class DirectoryPlaylist(Playlist): def __init__(self, parent=None): super(DirectoryPlaylist, self).__init__(parent) self._directories_urls = set() self._added_song_urls = set() self._tracks = [] self._qPlaylist = QMediaPlaylist(parent) self._qPlaylist.mediaAboutToBeInserted.connect( lambda s, e: self.mediaAboutToBeInserted.emit(s, e)) self._qPlaylist.mediaInserted.connect( lambda s, e: self.mediaInserted.emit(s, e)) self._qPlaylist.mediaAboutToBeRemoved.connect( lambda s, e: self.mediaAboutToBeRemoved.emit(s, e)) self._qPlaylist.mediaRemoved.connect( lambda s, e: self.mediaRemoved.emit(s, e)) self._qPlaylist.mediaChanged.connect( lambda s, e: self.mediaChanged.emit(s, e)) def songs(self): return self._tracks def albums_data(self): return self._albumsData def artists_data(self): return self._artistsData def __traverse_directory(self, url, func): songs = [] for root, dirs, files in os.walk(url): for file in files: abs_path = os.path.join(root, file) song = func(abs_path) if song: songs.append(song) return songs def is_empty(self): return not self._tracks def add_song(self, abs_path): if abs_path not in self._added_song_urls: url = QtCore.QUrl.fromLocalFile(abs_path) song = MediaFactory.create_media(abs_path) if not song: return None added = self._qPlaylist.addMedia(QMediaContent(url)) if not added: return None self._tracks.append(song) self._added_song_urls.add(abs_path) return song def remove_song(self, row): if row < 0 or row > self.song_count() - 1: return None if self._qPlaylist.currentIndex() == row: if row < self.song_count(): self._qPlaylist.setCurrentIndex(row + 1) else: self._qPlaylist.setCurrentIndex(row - 1) removed = self._qPlaylist.removeMedia(row) if not removed: return del self._tracks[row] url = self.get_song_abs_path(row) self._added_song_urls.discard(url) def add_directory(self, directory): if directory not in self._directories_urls: self._directories_urls.add(directory) songs = self.__traverse_directory(directory, self.add_song) return songs return None def add_directories(self, directories): songs = [] for directory in directories: if directory not in self._directories_urls: current_songs = self.add_directory(directory) if current_songs: songs.extend(current_songs) return songs def remove_directory(self, directory): if directory not in self._directories_urls: return False # raise Error self.__traverse_directory(directory, self.remove_song) def setCurrentIndex(self, index): self._qPlaylist.setCurrentIndex(index) def getCurrentIndex(self): return self._qPlaylist.currentIndex() def getCurrentSong(self): return self._qPlaylist.currentMedia() def clear(self): self._tracks = [] self._directories_urls = set() self._added_song_urls = set() self._qPlaylist.clear() @property def internalPlaylist(self): return self._qPlaylist def song_count(self): return len(self._tracks) def get_song_metadata(self, row, tags): if row < 0 or row > self.song_count() - 1: return None if not isinstance(tags, list): tags = [tags] return self._tracks[row].get_values(tags) def get_song(self, row): if row < 0 or row > self.song_count() - 1: return None return self._tracks[row] def get_song_title(self, row): if row < 0 or row > self.song_count() - 1: return None k, v = self.get_song_metadata(row, 'title').popitem() try: return v[0] except IndexError: return None def get_song_album(self, row): if row < 0 or row > self.song_count() - 1: return None k, v = self.get_song_metadata(row, 'album').popitem() try: return v[0] except IndexError: return None def get_song_artist(self, row): if row < 0 or row > self.song_count() - 1: return None k, v = self.get_song_metadata(row, 'artist').popitem() try: return v[0] except IndexError: return None def get_song_genre(self, row): if row < 0 or row > self.song_count() - 1: return None k, v = self.get_song_metadata(row, 'genre').popitem() try: return v[0] except IndexError: return None def get_song_abs_path(self, row): if row < 0 or row > self.song_count() - 1: return None return self._tracks[row].get_abs_path() def getDirectories(self): return self._directories_urls def getAddedSongUrls(self): return self._added_song_urls def __str__(self): return str(self._tracks) def __eq__(self, other): return (isinstance(other, self.__class__) and self._directories_urls == other._directories_urls and self._added_song_urls == other._added_song_urls)
def __init__(self, parent=None): """Initialize the QMainWindow widget. The window title, window icon, and window size are initialized here as well as the following widgets: QMediaPlayer, QMediaPlaylist, QMediaContent, QMenuBar, QToolBar, QLabel, QPixmap, QSlider, QDockWidget, QListWidget, QWidget, and QVBoxLayout. The connect signals for relavant widgets are also initialized. """ super(MusicPlayer, self).__init__(parent) self.setWindowTitle('Mosaic') window_icon = utilities.resource_filename('mosaic.images', 'icon.png') self.setWindowIcon(QIcon(window_icon)) self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63) # Initiates Qt objects to be used by MusicPlayer self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.playlist_location = defaults.Settings().playlist_path self.content = QMediaContent() self.menu = self.menuBar() self.toolbar = QToolBar() self.art = QLabel() self.pixmap = QPixmap() self.slider = QSlider(Qt.Horizontal) self.duration_label = QLabel() self.playlist_dock = QDockWidget('Playlist', self) self.library_dock = QDockWidget('Media Library', self) self.playlist_view = QListWidget() self.library_view = library.MediaLibraryView() self.library_model = library.MediaLibraryModel() self.preferences = configuration.PreferencesDialog() self.widget = QWidget() self.layout = QVBoxLayout(self.widget) self.duration = 0 self.playlist_dock_state = None self.library_dock_state = None # Sets QWidget() as the central widget of the main window self.setCentralWidget(self.widget) self.layout.setContentsMargins(0, 0, 0, 0) self.art.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) # Initiates the playlist dock widget and the library dock widget self.addDockWidget(defaults.Settings().dock_position, self.playlist_dock) self.playlist_dock.setWidget(self.playlist_view) self.playlist_dock.setVisible(defaults.Settings().playlist_on_start) self.playlist_dock.setFeatures(QDockWidget.DockWidgetClosable) self.addDockWidget(defaults.Settings().dock_position, self.library_dock) self.library_dock.setWidget(self.library_view) self.library_dock.setVisible(defaults.Settings().media_library_on_start) self.library_dock.setFeatures(QDockWidget.DockWidgetClosable) self.tabifyDockWidget(self.playlist_dock, self.library_dock) # Sets the range of the playback slider and sets the playback mode as looping self.slider.setRange(0, self.player.duration() / 1000) self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) # OSX system menu bar causes conflicts with PyQt5 menu bar if sys.platform == 'darwin': self.menu.setNativeMenuBar(False) # Initiates Settings in the defaults module to give access to settings.toml defaults.Settings() # Signals that connect to other methods when they're called self.player.metaDataChanged.connect(self.display_meta_data) self.slider.sliderMoved.connect(self.seek) self.player.durationChanged.connect(self.song_duration) self.player.positionChanged.connect(self.song_position) self.player.stateChanged.connect(self.set_state) self.playlist_view.itemActivated.connect(self.activate_playlist_item) self.library_view.activated.connect(self.open_media_library) self.playlist.currentIndexChanged.connect(self.change_index) self.playlist.mediaInserted.connect(self.initialize_playlist) self.playlist_dock.visibilityChanged.connect(self.dock_visiblity_change) self.library_dock.visibilityChanged.connect(self.dock_visiblity_change) self.preferences.dialog_media_library.media_library_line.textChanged.connect(self.change_media_library_path) self.preferences.dialog_view_options.dropdown_box.currentIndexChanged.connect(self.change_window_size) self.art.mousePressEvent = self.press_playback # Creating the menu controls, media controls, and window size of the music player self.menu_controls() self.media_controls() self.load_saved_playlist()
def __init__(self, parent=None): super(Player, self).__init__(parent) self.setWindowTitle("SongScreen") self.setFocusPolicy(Qt.StrongFocus) self.colorDialog = None self.trackInfo = "" self.statusInfo = "" self.duration = 0 self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.player.setPlaylist(self.playlist) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.metaDataChanged.connect(self.metaDataChanged) # self.playlist.currentIndexChanged.connect(self.playlistPositionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.bufferStatusChanged.connect(self.bufferingProgress) self.player.videoAvailableChanged.connect(self.videoAvailableChanged) self.player.error.connect(self.displayErrorMessage) # self.videoWidget = VideoWidget() # self.player.setVideoOutput(self.videoWidget) self.slider = MediaProgressWidget() # QSlider(Qt.Horizontal) self.markers = [] self.songtext_widget = SongTextWidget() self.songtext_widget.show() # self.playlistModel = PlaylistModel() # self.playlistModel.setPlaylist(self.playlist) # # self.playlistView = QListView() # self.playlistView.setModel(self.playlistModel) # self.playlistView.setCurrentIndex( # self.playlistModel.index(self.playlist.currentIndex(), 0)) # # self.playlistView.activated.connect(self.jump) self.slider.setRange(0, self.player.duration() / 1000) self.labelDuration = QLabel() self.slider.sliderMoved.connect(self.seek) # openButton = QPushButton("Open", clicked=self.open) controls = PlayerControlsWidget() controls.setState(self.player.state()) controls.setVolume(self.player.volume()) # controls.setMuted(controls.isMuted()) controls.play.connect(self.player.play) controls.pause.connect(self.player.pause) controls.stop.connect(self.stop_clicked) # controls.stop.connect(self.videoWidget.update) # controls.next.connect(self.playlist.next) # controls.previous.connect(self.previousClicked) controls.changeVolume.connect(self.player.setVolume) # controls.changeMuting.connect(self.player.setMuted) # controls.changeRate.connect(self.player.setPlaybackRate) self.player.stateChanged.connect(controls.setState) self.player.stateChanged.connect(self.setState) self.player.volumeChanged.connect(controls.setVolume) # self.player.mutedChanged.connect(controls.setMuted) # self.fullScreenButton = QPushButton("FullScreen") # self.fullScreenButton.setCheckable(True) # # self.colorButton = QPushButton("Color Options...") # self.colorButton.setEnabled(False) # self.colorButton.clicked.connect(self.showColorDialog) displayLayout = QHBoxLayout() # displayLayout.addWidget(self.videoWidget, 2) # displayLayout.addWidget(self.songtext_widget) # displayLayout.addWidget(self.playlistView) self.song_select_widget = SongSelectWidget() self.song_select_widget.song_selected.connect(self.load_song) self.screen_select_widget = ScreenSelectWidget() self.screen_select_widget.screen_selected.connect(self.display_lyrics_on_screen) self.screen_select_widget.active_screen = QApplication.desktop().screenNumber(self.songtext_widget) self.settings_button = QPushButton() self.settings_button.setText(self.tr("Settings...")) self.settings_button.clicked.connect(self.show_settings) sidebarLayout = QVBoxLayout() sidebarLayout.setContentsMargins(10, 1, 0, 1); sidebarLayout.addWidget(self.settings_button) sidebarLayout.addStretch(1); sidebarLayout.addWidget(self.screen_select_widget) displayLayout.addWidget(self.song_select_widget) displayLayout.addLayout(sidebarLayout) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) # controlLayout.addWidget(openButton) # controlLayout.addStretch(1) controlLayout.addWidget(controls) controlLayout.addStretch(1) controlLayout.addWidget(self.labelDuration) # controlLayout.addWidget(self.fullScreenButton) # controlLayout.addWidget(self.colorButton) layout = QVBoxLayout() layout.addLayout(displayLayout) hLayout = QHBoxLayout() hLayout.addWidget(self.slider) # hLayout.addWidget(self.labelDuration) layout.addLayout(hLayout) layout.addLayout(controlLayout) self.setLayout(layout) if not self.player.isAvailable(): QMessageBox.warning(self, "Service not available", "The QMediaPlayer object does not have a valid service.\n" "Please check the media service plugins are installed.") controls.setEnabled(False) self.playlistView.setEnabled(False) # openButton.setEnabled(False) self.colorButton.setEnabled(False) self.fullScreenButton.setEnabled(False) self.metaDataChanged() self._loading_audio = False self._finished_song = False self._lyrics_fading = False self._song_number = -1 self.settings = { 'font_size': 40, 'line_increment': 2, 'lyrics_language': '', } self._load_settings() self.settings_widget = SettingsWidget(self.settings, self.lyrics_path) self.settings_widget.font_size_changed.connect(self.songtext_widget.set_font_size) self.settings_widget.line_increment_changed.connect(self.songtext_widget.set_line_increment) self.settings_widget.language_changed.connect(self._language_changed) self.song_select_widget.reset(self.available_song_numbers)
class Player(QWidget): audio_path = "audio" lyrics_path = "lyrics" timings_path = os.path.join("lyrics", "timing") settings_path = "settings.json" fullScreenChanged = pyqtSignal(bool) def __init__(self, parent=None): super(Player, self).__init__(parent) self.setWindowTitle("SongScreen") self.setFocusPolicy(Qt.StrongFocus) self.colorDialog = None self.trackInfo = "" self.statusInfo = "" self.duration = 0 self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.player.setPlaylist(self.playlist) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.metaDataChanged.connect(self.metaDataChanged) # self.playlist.currentIndexChanged.connect(self.playlistPositionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.bufferStatusChanged.connect(self.bufferingProgress) self.player.videoAvailableChanged.connect(self.videoAvailableChanged) self.player.error.connect(self.displayErrorMessage) # self.videoWidget = VideoWidget() # self.player.setVideoOutput(self.videoWidget) self.slider = MediaProgressWidget() # QSlider(Qt.Horizontal) self.markers = [] self.songtext_widget = SongTextWidget() self.songtext_widget.show() # self.playlistModel = PlaylistModel() # self.playlistModel.setPlaylist(self.playlist) # # self.playlistView = QListView() # self.playlistView.setModel(self.playlistModel) # self.playlistView.setCurrentIndex( # self.playlistModel.index(self.playlist.currentIndex(), 0)) # # self.playlistView.activated.connect(self.jump) self.slider.setRange(0, self.player.duration() / 1000) self.labelDuration = QLabel() self.slider.sliderMoved.connect(self.seek) # openButton = QPushButton("Open", clicked=self.open) controls = PlayerControlsWidget() controls.setState(self.player.state()) controls.setVolume(self.player.volume()) # controls.setMuted(controls.isMuted()) controls.play.connect(self.player.play) controls.pause.connect(self.player.pause) controls.stop.connect(self.stop_clicked) # controls.stop.connect(self.videoWidget.update) # controls.next.connect(self.playlist.next) # controls.previous.connect(self.previousClicked) controls.changeVolume.connect(self.player.setVolume) # controls.changeMuting.connect(self.player.setMuted) # controls.changeRate.connect(self.player.setPlaybackRate) self.player.stateChanged.connect(controls.setState) self.player.stateChanged.connect(self.setState) self.player.volumeChanged.connect(controls.setVolume) # self.player.mutedChanged.connect(controls.setMuted) # self.fullScreenButton = QPushButton("FullScreen") # self.fullScreenButton.setCheckable(True) # # self.colorButton = QPushButton("Color Options...") # self.colorButton.setEnabled(False) # self.colorButton.clicked.connect(self.showColorDialog) displayLayout = QHBoxLayout() # displayLayout.addWidget(self.videoWidget, 2) # displayLayout.addWidget(self.songtext_widget) # displayLayout.addWidget(self.playlistView) self.song_select_widget = SongSelectWidget() self.song_select_widget.song_selected.connect(self.load_song) self.screen_select_widget = ScreenSelectWidget() self.screen_select_widget.screen_selected.connect(self.display_lyrics_on_screen) self.screen_select_widget.active_screen = QApplication.desktop().screenNumber(self.songtext_widget) self.settings_button = QPushButton() self.settings_button.setText(self.tr("Settings...")) self.settings_button.clicked.connect(self.show_settings) sidebarLayout = QVBoxLayout() sidebarLayout.setContentsMargins(10, 1, 0, 1); sidebarLayout.addWidget(self.settings_button) sidebarLayout.addStretch(1); sidebarLayout.addWidget(self.screen_select_widget) displayLayout.addWidget(self.song_select_widget) displayLayout.addLayout(sidebarLayout) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) # controlLayout.addWidget(openButton) # controlLayout.addStretch(1) controlLayout.addWidget(controls) controlLayout.addStretch(1) controlLayout.addWidget(self.labelDuration) # controlLayout.addWidget(self.fullScreenButton) # controlLayout.addWidget(self.colorButton) layout = QVBoxLayout() layout.addLayout(displayLayout) hLayout = QHBoxLayout() hLayout.addWidget(self.slider) # hLayout.addWidget(self.labelDuration) layout.addLayout(hLayout) layout.addLayout(controlLayout) self.setLayout(layout) if not self.player.isAvailable(): QMessageBox.warning(self, "Service not available", "The QMediaPlayer object does not have a valid service.\n" "Please check the media service plugins are installed.") controls.setEnabled(False) self.playlistView.setEnabled(False) # openButton.setEnabled(False) self.colorButton.setEnabled(False) self.fullScreenButton.setEnabled(False) self.metaDataChanged() self._loading_audio = False self._finished_song = False self._lyrics_fading = False self._song_number = -1 self.settings = { 'font_size': 40, 'line_increment': 2, 'lyrics_language': '', } self._load_settings() self.settings_widget = SettingsWidget(self.settings, self.lyrics_path) self.settings_widget.font_size_changed.connect(self.songtext_widget.set_font_size) self.settings_widget.line_increment_changed.connect(self.songtext_widget.set_line_increment) self.settings_widget.language_changed.connect(self._language_changed) self.song_select_widget.reset(self.available_song_numbers) @property def lyrics_language_path(self): path = QStandardPaths.locate(QStandardPaths.AppDataLocation, self.lyrics_path, QStandardPaths.LocateDirectory) return os.path.join(path, self.settings['lyrics_language']) @property def available_song_numbers(self): audios = set( [int(os.path.splitext(filename)[0]) for filename in os.listdir(self.audio_path) if filename[0] != '.']) try: lyrics = set( [int(os.path.splitext(filename)[0]) for filename in os.listdir(self.lyrics_language_path) if filename[0] != '.'] ) except (ValueError, FileNotFoundError): lyrics = set() return sorted(list(audios.intersection(lyrics))) def show_settings(self): self.settings_widget.hide() self.settings_widget.show() def display_lyrics_on_screen(self, screen_number): desktop = QApplication.desktop() if screen_number >= desktop.screenCount(): screen_number = desktop.screenNumber(self) rect = desktop.availableGeometry(screen_number) for _ in range(3): if screen_number != desktop.screenNumber(self): self.songtext_widget.setWindowFlags(Qt.FramelessWindowHint) self.songtext_widget.hide() self.songtext_widget.move(rect.x(), rect.y()) self.songtext_widget.resize(rect.width(), rect.height()) self.songtext_widget.showFullScreen() else: self.songtext_widget.setWindowFlags(Qt.WindowTitleHint) self.songtext_widget.hide() self.songtext_widget.move(rect.x(), rect.y()) self.songtext_widget.resize(self.songtext_widget.minimumSize()) self.songtext_widget.show() self.screen_select_widget.active_screen = screen_number self.activateWindow() def load_song(self, song_number): if self._song_number == song_number: self.seek(0) else: if self._song_number > 0: self._save_timings() self._song_number = song_number self.slider.dirty = False self._load_audio() self._load_lyrics() # self.player.play() def _load_audio(self): filename = os.path.join(self.audio_path, "{:03}.mp3".format(self._song_number)) self.playlist.clear() fileInfo = QFileInfo(filename) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) if fileInfo.suffix().lower() == 'm3u': self.playlist.load(url) else: self.playlist.addMedia(QMediaContent(url)) self._loading_audio = True self.player.play() def _load_lyrics(self): with open(os.path.join(self.lyrics_language_path, "{}.json".format(self._song_number)), 'r') as f: song_markers = json.load(f) self.markers = [] for m in song_markers['markers']: marker = MediaMarker(self.slider, m['name']) marker.text = m['text'] marker.progress = 0.0 self.markers.append(marker) self.songtext_widget.title = "{} {}".format(self._song_number, song_markers['title']) self.songtext_widget.markers = self.markers self.songtext_widget.fade_in() try: with open(os.path.join(self.timings_path, "{}.json".format(self._song_number)), 'r') as f: timings = json.load(f) for m, t in zip(self.markers, timings): m.progress = t except FileNotFoundError: pass self.slider.markers = self.markers def _language_changed(self, _): available_song_numbers = self.available_song_numbers self.song_select_widget.reset(available_song_numbers) if self._song_number in available_song_numbers: self._load_lyrics() # def open(self): # fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files") # self.addToPlaylist(fileNames) # # def addToPlaylist(self, fileNames): # for name in fileNames: # fileInfo = QFileInfo(name) # if fileInfo.exists(): # url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) # if fileInfo.suffix().lower() == 'm3u': # self.playlist.load(url) # else: # self.playlist.addMedia(QMediaContent(url)) # else: # url = QUrl(name) # if url.isValid(): # self.playlist.addMedia(QMediaContent(url)) def durationChanged(self, duration): duration /= 1000 self.duration = duration self.slider.setMaximum(duration) if self._loading_audio: self._loading_audio = False line_total = 0 for marker in self.markers: line_total += marker.linecount - 1 silence_ratio = 5.0 / self.duration offset = 1.8 / line_total linecount = 0 for marker in self.markers: if marker.progress == 0.0: marker.progress = offset + (1 - offset) * (1 - silence_ratio) * linecount / line_total linecount += marker.linecount - 1 self.player.pause() @property def _should_fade_out(self): return self.player.position() / 1000 >= self.duration - 5 def positionChanged(self, progress): progress /= 1000 if not self.slider.isSliderDown(): self.slider.setValue(progress) self.updateDurationInfo(progress) if self.duration > 0: # if self.player.state() == QMediaPlayer.PlayingState: self.songtext_widget.progress = progress / self.duration if self._should_fade_out: self._fade_out_lyrics() def _fade_out_lyrics(self): if not self._lyrics_fading: self._lyrics_fading = True self.songtext_widget.fade_out() def metaDataChanged(self): if self.player.isMetaDataAvailable(): self.setTrackInfo("%s - %s" % ( self.player.metaData(QMediaMetaData.AlbumArtist), self.player.metaData(QMediaMetaData.Title))) def previousClicked(self): # Go to the previous track if we are within the first 5 seconds of # playback. Otherwise, seek to the beginning. if self.player.position() <= 5000: self.playlist.previous() else: self.player.setPosition(0) def jump(self, index): if index.isValid(): self.playlist.setCurrentIndex(index.row()) self.player.play() def seek(self, seconds): self.player.setPosition(seconds * 1000) def setState(self, status): if status == QMediaPlayer.StoppedState: self._finished_song = True elif status == QMediaPlayer.PlayingState: if self._finished_song or (self._lyrics_fading and not self._should_fade_out): self._finished_song = False self._lyrics_fading = False self.songtext_widget.fade_in() def stop_clicked(self): self.player.stop() self._fade_out_lyrics() def statusChanged(self, status): self.handleCursor(status) if status == QMediaPlayer.LoadingMedia: self.setStatusInfo("Loading...") elif status == QMediaPlayer.StalledMedia: self.setStatusInfo("Media Stalled") elif status == QMediaPlayer.EndOfMedia: QApplication.alert(self) elif status == QMediaPlayer.InvalidMedia: self.displayErrorMessage() else: self.setStatusInfo("") def handleCursor(self, status): if status in (QMediaPlayer.LoadingMedia, QMediaPlayer.BufferingMedia, QMediaPlayer.StalledMedia): self.setCursor(Qt.BusyCursor) else: self.unsetCursor() def bufferingProgress(self, progress): self.setStatusInfo("Buffering %d%" % progress) def videoAvailableChanged(self, available): if available: self.fullScreenButton.clicked.connect( self.videoWidget.setFullScreen) self.videoWidget.fullScreenChanged.connect( self.fullScreenButton.setChecked) if self.fullScreenButton.isChecked(): self.videoWidget.setFullScreen(True) else: self.fullScreenButton.clicked.disconnect( self.videoWidget.setFullScreen) self.videoWidget.fullScreenChanged.disconnect( self.fullScreenButton.setChecked) self.videoWidget.setFullScreen(False) self.colorButton.setEnabled(available) def setTrackInfo(self, info): self.trackInfo = info # if self.statusInfo != "": # self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo)) # else: # self.setWindowTitle(self.trackInfo) def setStatusInfo(self, info): self.statusInfo = info # if self.statusInfo != "": # self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo)) # else: # self.setWindowTitle(self.trackInfo) def displayErrorMessage(self): self.setStatusInfo(self.player.errorString()) def updateDurationInfo(self, currentInfo): duration = self.duration if currentInfo or duration: currentTime = QTime((currentInfo / 3600) % 60, (currentInfo / 60) % 60, currentInfo % 60, (currentInfo * 1000) % 1000) totalTime = QTime((duration / 3600) % 60, (duration / 60) % 60, duration % 60, (duration * 1000) % 1000); format = 'hh:mm:ss' if duration > 3600 else 'mm:ss' tStr = currentTime.toString(format) + " / " + totalTime.toString(format) else: tStr = "" self.labelDuration.setText(tStr) def showColorDialog(self): if self.colorDialog is None: brightnessSlider = QSlider(Qt.Horizontal) brightnessSlider.setRange(-100, 100) brightnessSlider.setValue(self.videoWidget.brightness()) brightnessSlider.sliderMoved.connect( self.videoWidget.setBrightness) self.videoWidget.brightnessChanged.connect( brightnessSlider.setValue) contrastSlider = QSlider(Qt.Horizontal) contrastSlider.setRange(-100, 100) contrastSlider.setValue(self.videoWidget.contrast()) contrastSlider.sliderMoved.connect(self.videoWidget.setContrast) self.videoWidget.contrastChanged.connect(contrastSlider.setValue) hueSlider = QSlider(Qt.Horizontal) hueSlider.setRange(-100, 100) hueSlider.setValue(self.videoWidget.hue()) hueSlider.sliderMoved.connect(self.videoWidget.setHue) self.videoWidget.hueChanged.connect(hueSlider.setValue) saturationSlider = QSlider(Qt.Horizontal) saturationSlider.setRange(-100, 100) saturationSlider.setValue(self.videoWidget.saturation()) saturationSlider.sliderMoved.connect( self.videoWidget.setSaturation) self.videoWidget.saturationChanged.connect( saturationSlider.setValue) layout = QFormLayout() layout.addRow("Brightness", brightnessSlider) layout.addRow("Contrast", contrastSlider) layout.addRow("Hue", hueSlider) layout.addRow("Saturation", saturationSlider) button = QPushButton("Close") layout.addRow(button) self.colorDialog = QDialog(self) self.colorDialog.setWindowTitle("Color Options") self.colorDialog.setLayout(layout) button.clicked.connect(self.colorDialog.close) self.colorDialog.show() def closeEvent(self, close_event): self._save_timings() self._save_settings() self.songtext_widget.close() self.settings_widget.close() def keyPressEvent(self, key_event): if key_event.key() == Qt.Key_Space: key_event.accept() if self.player.state() == QMediaPlayer.PlayingState: self.player.pause() elif self.player.state() in [QMediaPlayer.PausedState, QMediaPlayer.StoppedState]: self.player.play() elif key_event.key() == Qt.Key_M: key_event.accept() self.slider.set_closest_marker_to_current_progress() def _save_timings(self): if self.slider.dirty: with open(os.path.join(self.timings_path, "{}.json".format(self._song_number)), 'w') as f: json.dump([marker.progress for marker in self.markers], f, indent=2) def _save_settings(self): # TODO : refactor and use QSettings directly # with open(self.settings_path, 'w') as f: self.settings.update({ 'lyrics_screen': QApplication.desktop().screenNumber(self.songtext_widget), 'control_window_position': self.pos(), }) # json.dump(self.settings, f, indent=2) settings = QSettings("Maccesch", "SongScreen") for key, value in self.settings.items(): settings.setValue(key, value) def _load_settings(self): # try: # with open(self.settings_path, 'r') as f: # settings = json.load(f) settings = QSettings("Maccesch", "SongScreen") if settings.contains('lyrics_screen'): self.display_lyrics_on_screen(settings.value('lyrics_screen')) if settings.contains('control_window_position'): self.move(settings.value('control_window_position')) for key in settings.allKeys(): self.settings[key] = settings.value(key) # self.settings.update(settings) self.songtext_widget.set_font_size(self.settings['font_size']) self.songtext_widget.set_line_increment(self.settings['line_increment']) # except (FileNotFoundError, ValueError): # pass if not os.path.exists(self.lyrics_language_path) or not self.settings['lyrics_language']: languages = list( filter(lambda p: os.path.isdir(os.path.join(self.lyrics_path, p)) and p != "timings", os.listdir(self.lyrics_path)) ) self.settings['lyrics_language'] = languages[0] if languages else ""
def __init__(self, playlist, parent=None): # create player super(Player, self).__init__(parent) self.trackInfo = '' self.statusInfo = '' self.duration = 0 # create player object self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.name = 'Current playlist' self.player.setPlaylist(self.playlist) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.metaDataChanged.connect(self.metaDataChanged) self.playlist.currentIndexChanged.connect(self.playlistPositionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.bufferStatusChanged.connect(self.bufferingProgress) # self.player.videoAvailableChanged.connect(self.videoAvailableChanged) self.player.error.connect(self.displayErrorMessage) # connect with VideoWidget # self.videoWidget = VideoWidget() # self.player.setVideoOutput(self.videoWidget) # connect with PlaylistModel self.playlistModel = PlaylistModel() self.playlistModel.setPlaylist(self.playlist) self.playlistView = Qt.QListView() self.playlistView.setModel(self.playlistModel) self.playlistView.setCurrentIndex(self.playlistModel.index( self.playlist.currentIndex(), 0)) # change to next song self.playlistView.activated.connect(self.jump) self.slider = Qt.QSlider(QtCore.Qt.Horizontal) self.slider.setRange(0, self.player.duration() / 1000) self.labelDuration = Qt.QLabel() self.slider.sliderMoved.connect(self.seek) # create histogram self.labelHistogram = Qt.QLabel() self.labelHistogram.setText('Histogram: ') self.histogram = HistogramWidget() histogramLayout = Qt.QHBoxLayout() histogramLayout.addWidget(self.labelHistogram) histogramLayout.addWidget(self.histogram, 1) # create videoProbe self.videoProbe = Qt.QVideoProbe() self.videoProbe.videoFrameProbed.connect(self.histogram.processFrame) self.videoProbe.setSource(self.player) # add control controls = Controllers() controls.setState(self.player.state()) controls.setVolume(self.player.volume()) controls.setMuted(controls.isMuted()) # connect player's controls with Controllers controls.play.connect(self.player.play) controls.pause.connect(self.player.pause) controls.stop.connect(self.player.stop) controls.next.connect(self.playlist.next) controls.previous.connect(self.previousAction) controls.changeVolume.connect(self.player.setVolume) controls.changeMuting.connect(self.player.setMuted) # setPlaybackRate is from QMediaPlayer controls.changeSpeed.connect(self.player.setPlaybackRate) # controls.stop.connect(self.videoWidget.update) self.player.stateChanged.connect(controls.setState) self.player.volumeChanged.connect(controls.setVolume) self.player.mutedChanged.connect(controls.setMuted) # create fullScreenButton # self.fullScreenButton = Qt.QPushButton('FullScreen') # self.fullScreenButton.setCheckable(True) # displayLayout displayLayout = Qt.QHBoxLayout() # displayLayout.addWidget(self.videoWidget, 2) displayLayout.addWidget(self.playlistView) # controlLayout controlLayout = Qt.QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) # connect controlLayout with controls controlLayout.addWidget(controls) controlLayout.addStretch(1) # connect controlLayout with fullScreenButton # controlLayout.addWidget(self.fullScreenButton) # visualize player layout = Qt.QVBoxLayout() layout.addLayout(displayLayout) # layout for sliding song playing hLayout = Qt.QHBoxLayout() hLayout.addWidget(self.slider) hLayout.addWidget(self.labelDuration) layout.addLayout(hLayout) layout.addLayout(controlLayout) layout.addLayout(histogramLayout) # set icon self.setWindowIcon(Qt.QIcon('favicon.ico')) # create menus toolBar = Qt.QToolBar() # create basic actions self.createActions() # create simple button to repeat song self.repeatButton = Qt.QToolButton() self.repeatButton.setDefaultAction(self.repeatAct) # create playOnceButton self.playOnceButton = Qt.QToolButton() self.playOnceButton.setDefaultAction(self.playOnceAct) self.playOnceButton.setEnabled(False) # create shuffleButton self.shuffleButton = Qt.QToolButton() self.shuffleButton.setDefaultAction(self.shuffleAct) # create sequentialButton self.sequentialButton = Qt.QToolButton() self.sequentialButton.setDefaultAction(self.sequentialAct) # create fileButton for fileMenu fileButton = Qt.QToolButton() fileButton.setText('File') fileButton.setPopupMode(Qt.QToolButton.MenuButtonPopup) fileButton.setMenu(self.popFileMenu()) # create editButton for editMenu closeButton = Qt.QToolButton() closeButton.setText('Edit') closeButton.setDefaultAction(self.fileCloseAct) # display in toolBar these buttons toolBar.addWidget(self.repeatButton) toolBar.addWidget(self.playOnceButton) toolBar.addWidget(self.shuffleButton) toolBar.addWidget(self.sequentialButton) toolBar.addWidget(fileButton) toolBar.addWidget(closeButton) # add toolBar to layout of the player layout.addWidget(toolBar) layout.addWidget(Qt.QGroupBox()) self.setWindowTitle("Python Music Player") self.setLayout(layout) if not self.player.isAvailable(): Qt.QMessageBox(self, 'Unavailable service') # self.displayErrorMessage() controls.setEnabled(False) self.playlistView.setEnabled(False) self.fullScreenButton.setEnabled(False) self.metaDataChanged() self.addToPlaylist(playlist)
class Player(Qt.QWidget): """docstring for Player""" fullScreenChanged = Qt.pyqtSignal(bool) def __init__(self, playlist, parent=None): # create player super(Player, self).__init__(parent) self.trackInfo = '' self.statusInfo = '' self.duration = 0 # create player object self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.name = 'Current playlist' self.player.setPlaylist(self.playlist) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.metaDataChanged.connect(self.metaDataChanged) self.playlist.currentIndexChanged.connect(self.playlistPositionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.bufferStatusChanged.connect(self.bufferingProgress) # self.player.videoAvailableChanged.connect(self.videoAvailableChanged) self.player.error.connect(self.displayErrorMessage) # connect with VideoWidget # self.videoWidget = VideoWidget() # self.player.setVideoOutput(self.videoWidget) # connect with PlaylistModel self.playlistModel = PlaylistModel() self.playlistModel.setPlaylist(self.playlist) self.playlistView = Qt.QListView() self.playlistView.setModel(self.playlistModel) self.playlistView.setCurrentIndex(self.playlistModel.index( self.playlist.currentIndex(), 0)) # change to next song self.playlistView.activated.connect(self.jump) self.slider = Qt.QSlider(QtCore.Qt.Horizontal) self.slider.setRange(0, self.player.duration() / 1000) self.labelDuration = Qt.QLabel() self.slider.sliderMoved.connect(self.seek) # create histogram self.labelHistogram = Qt.QLabel() self.labelHistogram.setText('Histogram: ') self.histogram = HistogramWidget() histogramLayout = Qt.QHBoxLayout() histogramLayout.addWidget(self.labelHistogram) histogramLayout.addWidget(self.histogram, 1) # create videoProbe self.videoProbe = Qt.QVideoProbe() self.videoProbe.videoFrameProbed.connect(self.histogram.processFrame) self.videoProbe.setSource(self.player) # add control controls = Controllers() controls.setState(self.player.state()) controls.setVolume(self.player.volume()) controls.setMuted(controls.isMuted()) # connect player's controls with Controllers controls.play.connect(self.player.play) controls.pause.connect(self.player.pause) controls.stop.connect(self.player.stop) controls.next.connect(self.playlist.next) controls.previous.connect(self.previousAction) controls.changeVolume.connect(self.player.setVolume) controls.changeMuting.connect(self.player.setMuted) # setPlaybackRate is from QMediaPlayer controls.changeSpeed.connect(self.player.setPlaybackRate) # controls.stop.connect(self.videoWidget.update) self.player.stateChanged.connect(controls.setState) self.player.volumeChanged.connect(controls.setVolume) self.player.mutedChanged.connect(controls.setMuted) # create fullScreenButton # self.fullScreenButton = Qt.QPushButton('FullScreen') # self.fullScreenButton.setCheckable(True) # displayLayout displayLayout = Qt.QHBoxLayout() # displayLayout.addWidget(self.videoWidget, 2) displayLayout.addWidget(self.playlistView) # controlLayout controlLayout = Qt.QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) # connect controlLayout with controls controlLayout.addWidget(controls) controlLayout.addStretch(1) # connect controlLayout with fullScreenButton # controlLayout.addWidget(self.fullScreenButton) # visualize player layout = Qt.QVBoxLayout() layout.addLayout(displayLayout) # layout for sliding song playing hLayout = Qt.QHBoxLayout() hLayout.addWidget(self.slider) hLayout.addWidget(self.labelDuration) layout.addLayout(hLayout) layout.addLayout(controlLayout) layout.addLayout(histogramLayout) # set icon self.setWindowIcon(Qt.QIcon('favicon.ico')) # create menus toolBar = Qt.QToolBar() # create basic actions self.createActions() # create simple button to repeat song self.repeatButton = Qt.QToolButton() self.repeatButton.setDefaultAction(self.repeatAct) # create playOnceButton self.playOnceButton = Qt.QToolButton() self.playOnceButton.setDefaultAction(self.playOnceAct) self.playOnceButton.setEnabled(False) # create shuffleButton self.shuffleButton = Qt.QToolButton() self.shuffleButton.setDefaultAction(self.shuffleAct) # create sequentialButton self.sequentialButton = Qt.QToolButton() self.sequentialButton.setDefaultAction(self.sequentialAct) # create fileButton for fileMenu fileButton = Qt.QToolButton() fileButton.setText('File') fileButton.setPopupMode(Qt.QToolButton.MenuButtonPopup) fileButton.setMenu(self.popFileMenu()) # create editButton for editMenu closeButton = Qt.QToolButton() closeButton.setText('Edit') closeButton.setDefaultAction(self.fileCloseAct) # display in toolBar these buttons toolBar.addWidget(self.repeatButton) toolBar.addWidget(self.playOnceButton) toolBar.addWidget(self.shuffleButton) toolBar.addWidget(self.sequentialButton) toolBar.addWidget(fileButton) toolBar.addWidget(closeButton) # add toolBar to layout of the player layout.addWidget(toolBar) layout.addWidget(Qt.QGroupBox()) self.setWindowTitle("Python Music Player") self.setLayout(layout) if not self.player.isAvailable(): Qt.QMessageBox(self, 'Unavailable service') # self.displayErrorMessage() controls.setEnabled(False) self.playlistView.setEnabled(False) self.fullScreenButton.setEnabled(False) self.metaDataChanged() self.addToPlaylist(playlist) # create fileMenu def popFileMenu(self): aMenu = Qt.QMenu(self) aMenu.addAction(self.fileOpenAct) aMenu.addAction(self.fileCloseAct) return aMenu def createActions(self): self.repeatAct = Qt.QAction('Repeat', self, triggered=self.repeatSong) self.playOnceAct = Qt.QAction( 'Play once', self, triggered=self.playOnceSong) self.shuffleAct = Qt.QAction( 'Shuffle', self, triggered=self.playlist.shuffle) self.sequentialAct = Qt.QAction( 'Sequential', self, triggered=self.playSequential) self.fileOpenAct = Qt.QAction('Open', self, triggered=self.open) self.fileOpenAct.setShortcut('Ctrl+O') self.fileCloseAct = Qt.QAction('Close', self, triggered=self.close) self.fileCloseAct.setShortcut('Ctrl+Q') def repeatSong(self): self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop) self.repeatButton.setEnabled(False) self.playOnceButton.setEnabled(True) def playOnceSong(self): self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) self.playOnceButton.setEnabled(False) self.repeatButton.setEnabled(True) # unproperly used def playSequential(self): self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) # get and display song duration def durationChanged(self, duration): duration /= 1000 self.duration = duration self.slider.setMaximum(duration) # change slider position def positionChanged(self, progress): progress /= 1000 if not self.slider.isSliderDown(): self.slider.setValue(progress) self.updateDurationInfo(progress) def updateDurationInfo(self, currentInfo): duration = self.duration if currentInfo or duration: currentTime = QtCore.QTime( (currentInfo / 3600) % 60, # hours (currentInfo / 60) % 60, # minutes currentInfo % 60, # seconds (currentInfo * 1000) % 1000) # miliseconds totalTime = QtCore.QTime( (duration / 3600) % 60, # hours (duration / 60) % 60, # minutes duration % 60, # seconds (duration * 1000) % 1000) # miliseconds formating = 'hh:mm:ss' if duration > 3600 else 'mm:ss' toString = (currentTime.toString(formating) + ' / ' + totalTime.toString(formating)) else: toString = '' self.labelDuration.setText(toString) def metaDataChanged(self): if self.player.isMetaDataAvailable(): self.setTrackInfo('{0} - {1}'.format( self.player.metaData(Qt.QMediaMetaData.AlbumArtist), self.player.metaData(Qt.QMediaMetaData.Title))) def setTrackInfo(self, info): self.trackInfo = info if self.statusInfo: self.setWindowTitle('{0} | {1}'.format( self.trackInfo, self.statusInfo)) else: self.setWindowTitle(self.trackInfo) def playlistPositionChanged(self, position): self.playlistView.setCurrentIndex( self.playlistModel.index(position, 0)) def statusChanged(self, status): self.handleCursor(status) if status == QMediaPlayer.LoadingMedia: self.setStatusInfo('Loading...') elif status == QMediaPlayer.StalledMedia: self.setStatusInfo('Media Stalled') elif status == QMediaPlayer.EndOfMedia: Qt.QApplication.alert(self) elif status == QMediaPlayer.InvalidMedia: self.displayErrorMessage() else: self.setStatusInfo('') def handleCursor(self, status): if status in [QMediaPlayer.LoadingMedia, QMediaPlayer.BufferingMedia, QMediaPlayer.StalledMedia]: self.setCursor(QtCore.Qt.BusyCursor) else: self.unsetCursor() def setStatusInfo(self, info): self.statusInfo = info if self.statusInfo: self.setWindowTitle('{0} | {1}'.format( self.trackInfo, self.statusInfo)) else: self.setWindowTitle(self.trackInfo) def bufferingProgress(self, progress): self.setStatusInfo('Buffering {0}'.format(progress)) def displayErrorMessage(self): self.statusInfo(self.player.errorString()) def jump(self, index): if index.isValid(): self.playlist.setCurrentIndex(index.row()) self.player.play() def seek(self, seconds): self.player.setPosition(seconds * 1000) def previousAction(self): self.playlist.previous() def close(self): choice = Qt.QMessageBox.question( self, 'Close', 'Close the app?', Qt.QMessageBox.Yes | Qt.QMessageBox.No) if choice == Qt.QMessageBox.Yes: sys.exit() def open(self): names, _ = Qt.QFileDialog.getOpenFileNames(self, 'Open Files') # ['/home/milka/Documents/MusicPlayer/song.mp3'] self.addToPlaylist(names) def addToPlaylist(self, names): for name in names: fileInfo = Qt.QFileInfo(name) if fileInfo.exists(): url = QtCore.QUrl.fromLocalFile(fileInfo.absoluteFilePath()) # save_to_db song url create_song( url.path(), self.duration, playlist_name=self.name) if fileInfo.suffix().lower() == 'm3u': self.playlist.load(url) else: self.playlist.addMedia(Qt.QMediaContent(url)) else: url = QtCore.QUrl(name) if url.isValid(): self.playlist.addMedia(Qt.QMediaContent(url))
class ApplicationWindow(QtWidgets.QMainWindow): global wavFileName global fig,chartFig global duration, counterClick global colorName, text_ global startAnnotation, endTimeToPlay # >> QtMultimedia Signals #---------------------- play = pyqtSignal() pause = pyqtSignal() stop = pyqtSignal() def __init__(self): global playerStarted global wavFileName, fig, chartFig global playerStarted, durationFlag, duration global colorName, text_, counterClick global startAnnotation, endTimeToPlay QtWidgets.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.main_widget = QtWidgets.QWidget(self) playerStarted = False #DEFINE PLAYER-PLAYLIST #---------------------- self.source = QtCore.QUrl.fromLocalFile(os.path.abspath(wavFileName)) self.content = QMediaContent(self.source) self.player = QMediaPlayer() self.playlist = QMediaPlaylist(self) self.playlist.addMedia(self.content) self.player.setPlaylist(self.playlist) # >> Define annotations and gantt chart #---------------------- self.wave = Waveform() fig = self.wave self.chart = Chart() chartFig = self.chart # >> Define player buttons #---------------------- playButton = QPushButton("Play") pauseButton = QPushButton("Pause") stopButton = QPushButton("Stop") # >> Define layouts #---------------------- waveLayout = QVBoxLayout() waveLayout.addWidget(self.wave) waveLayout.addWidget(self.chart) line = QFrame() line.setFrameShape(QFrame.VLine) line.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Expanding) waveLayout.addWidget(line) #Buttons layout buttonLayout = QVBoxLayout() buttonLayout.addWidget(playButton) buttonLayout.addWidget(pauseButton) buttonLayout.addWidget(stopButton) buttonLayout.setAlignment(Qt.AlignTop) # >> Specify final layout align #---------------------- layout = QHBoxLayout(self.main_widget) layout.addLayout(waveLayout) layout.addLayout(buttonLayout) # >> Define buttons connections #---------------------- playButton.clicked.connect(self.Play) pauseButton.clicked.connect(self.Pause) stopButton.clicked.connect(self.Stop) self.main_widget.setFocus() self.setCentralWidget(self.main_widget) # PLAYER BUTTON FUNCTIONS # >> Play audio (whole signal or segment) #---------------------- def Play(self): global playerStarted global durationFlag global duration, counterClick global startTimeToPlay, endTimeToPlay, first #GET CLICKS FROM WAVEFORM #---------------------- #Initialize connection-position ONCE if not playerStarted: #10ms for changePosition -> Not Delaying self.player.positionChanged.connect(self.checkPositionToStop) self.player.setNotifyInterval(10) if durationFlag==0: playerStarted = True startTimeToPlay = 0 self.start = startTimeToPlay self.end = duration*1000 - 10 endTimeToPlay = self.end counterClick = 3 elif durationFlag==1: playerStarted = True self.start = startTimeToPlay self.end = duration*1000 - 10 endTimeToPlay = self.end counterClick = 3 elif durationFlag==2: playerStarted = True self.start = startTimeToPlay self.end = endTimeToPlay self.player.setPosition(self.start) playFlag = True self.player.play() # >> Pause audio playing #---------------------- def Pause(self): #Not begging from self.start playerStarted = True self.player.setPosition(self.time_) self.player.pause() # >> Stop audio playing #---------------------- def Stop(self): self.player.stop() #Begin again segment self.start = startTimeToPlay self.player.setPosition(self.start) # >> Check ms in audio to stop play #---------------------- def checkPositionToStop(self): self.time_ = self.player.position() print self.time_ if self.time_ >= self.end: self.Stop() self.player.setPosition(self.start) def fileQuit(self): self.close() def closeEvent(self, ce): self.fileQuit()
@file: test.test_mp3.py @description: ''' from PyQt5.QtWidgets import QApplication, QPushButton from PyQt5.QtMultimedia import QMediaPlayer, QMediaPlaylist, QMediaContent from PyQt5.QtCore import QUrl __Author__ = "By: Irony.\"[讽刺]\nQQ: 892768447\nEmail: [email protected]" __Copyright__ = "Copyright (c) 2015 Irony.\"[讽刺]" __Version__ = "Version 1.0" app = QApplication([]) # 播放列表 playlist = QMediaPlaylist() _list = [] for i in range(1, 12): print("../data/lolita/voice/kiana_%d.mp3" % i) _list.append(QMediaContent(QUrl("../data/lolita/voice/kiana_%d.mp3" % i))) playlist.addMedia(_list) # 只播放当前的 playlist.setPlaybackMode(QMediaPlaylist.CurrentItemOnce) player = QMediaPlayer() # 设置播放列表 player.setPlaylist(playlist) # 设置音量 player.setVolume(100)
def __init__(self, playlist, parent=None): super(Player, self).__init__(parent) self.colorDialog = None self.trackInfo = "" self.statusInfo = "" self.duration = 0 self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.player.setPlaylist(self.playlist) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.metaDataChanged.connect(self.metaDataChanged) self.playlist.currentIndexChanged.connect(self.playlistPositionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.bufferStatusChanged.connect(self.bufferingProgress) self.player.videoAvailableChanged.connect(self.videoAvailableChanged) self.player.error.connect(self.displayErrorMessage) self.videoWidget = VideoWidget() self.player.setVideoOutput(self.videoWidget) self.playlistModel = PlaylistModel() self.playlistModel.setPlaylist(self.playlist) self.playlistView = QListView() self.playlistView.setModel(self.playlistModel) self.playlistView.setCurrentIndex( self.playlistModel.index(self.playlist.currentIndex(), 0)) self.playlistView.activated.connect(self.jump) self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, self.player.duration() / 1000) self.labelDuration = QLabel() self.slider.sliderMoved.connect(self.seek) self.labelHistogram = QLabel() self.labelHistogram.setText("Histogram:") self.histogram = HistogramWidget() histogramLayout = QHBoxLayout() histogramLayout.addWidget(self.labelHistogram) histogramLayout.addWidget(self.histogram, 1) self.probe = QVideoProbe() self.probe.videoFrameProbed.connect(self.histogram.processFrame) self.probe.setSource(self.player) openButton = QPushButton("Open", clicked=self.open) controls = PlayerControls() controls.setState(self.player.state()) controls.setVolume(self.player.volume()) controls.setMuted(controls.isMuted()) controls.play.connect(self.player.play) controls.pause.connect(self.player.pause) controls.stop.connect(self.player.stop) controls.next.connect(self.playlist.next) controls.previous.connect(self.previousClicked) controls.changeVolume.connect(self.player.setVolume) controls.changeMuting.connect(self.player.setMuted) controls.changeRate.connect(self.player.setPlaybackRate) controls.stop.connect(self.videoWidget.update) self.player.stateChanged.connect(controls.setState) self.player.volumeChanged.connect(controls.setVolume) self.player.mutedChanged.connect(controls.setMuted) self.fullScreenButton = QPushButton("FullScreen") self.fullScreenButton.setCheckable(True) self.colorButton = QPushButton("Color Options...") self.colorButton.setEnabled(False) self.colorButton.clicked.connect(self.showColorDialog) displayLayout = QHBoxLayout() displayLayout.addWidget(self.videoWidget, 2) displayLayout.addWidget(self.playlistView) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(openButton) controlLayout.addStretch(1) controlLayout.addWidget(controls) controlLayout.addStretch(1) controlLayout.addWidget(self.fullScreenButton) controlLayout.addWidget(self.colorButton) layout = QVBoxLayout() layout.addLayout(displayLayout) hLayout = QHBoxLayout() hLayout.addWidget(self.slider) hLayout.addWidget(self.labelDuration) layout.addLayout(hLayout) layout.addLayout(controlLayout) layout.addLayout(histogramLayout) self.setLayout(layout) if not self.player.isAvailable(): QMessageBox.warning(self, "Service not available", "The QMediaPlayer object does not have a valid service.\n" "Please check the media service plugins are installed.") controls.setEnabled(False) self.playlistView.setEnabled(False) openButton.setEnabled(False) self.colorButton.setEnabled(False) self.fullScreenButton.setEnabled(False) self.metaDataChanged() self.addToPlaylist(playlist)
class LolitaPlayer(QMediaPlayer): """控制萝莉声音""" def __init__(self, playList = [], ddir = "data", parent = None): super(LolitaPlayer, self).__init__(parent) try: # 播放列表 self.playList = QMediaPlaylist(parent) # 设置只播放一次 self.playList.setPlaybackMode(QMediaPlaylist.CurrentItemOnce) # 读取配置文件中的音乐路径 self._playList = playList # 添加到列表里 self.playList.addMedia([QMediaContent(QUrl(item[1].format(DATA_DIR = ddir))) for item in self._playList]) self.playList.setCurrentIndex(0) # 设置播放列表 self.setPlaylist(self.playList) # 设置音量 self.setVolume(100) except Exception as e: traceback.print_exc(e) def __del__(self): if hasattr(self, "playList"): del self.playList def currentIndex(self): if hasattr(self, "playList"): return self.playList.currentIndex() return 0 def mediaCount(self): if hasattr(self, "_playList"): return len(self._playList) return 0 def setCurrentIndex(self, i): if hasattr(self, "playList"): self.playList.setCurrentIndex(i) def getText(self, i): """获取当前歌曲对应的文字""" if hasattr(self, "_playList"): try: return self._playList[i][0] except Exception as e: traceback.print_exc(e) return "" def play(self, i): """播放指定的歌曲""" if hasattr(self, "playList"): self.playList.setCurrentIndex(i) # 切换到第几首 super(LolitaPlayer, self).play() # 播放一次
class Player(QWidget): fullScreenChanged = pyqtSignal(bool) def __init__(self, playlist, parent=None): super(Player, self).__init__(parent) self.colorDialog = None self.trackInfo = "" self.statusInfo = "" self.duration = 0 self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.player.setPlaylist(self.playlist) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.metaDataChanged.connect(self.metaDataChanged) self.playlist.currentIndexChanged.connect(self.playlistPositionChanged) self.player.mediaStatusChanged.connect(self.statusChanged) self.player.bufferStatusChanged.connect(self.bufferingProgress) self.player.videoAvailableChanged.connect(self.videoAvailableChanged) self.player.error.connect(self.displayErrorMessage) self.videoWidget = VideoWidget() self.player.setVideoOutput(self.videoWidget) self.playlistModel = PlaylistModel() self.playlistModel.setPlaylist(self.playlist) self.playlistView = QListView() self.playlistView.setModel(self.playlistModel) self.playlistView.setCurrentIndex( self.playlistModel.index(self.playlist.currentIndex(), 0)) self.playlistView.activated.connect(self.jump) self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, self.player.duration() / 1000) self.labelDuration = QLabel() self.slider.sliderMoved.connect(self.seek) self.labelHistogram = QLabel() self.labelHistogram.setText("Histogram:") self.histogram = HistogramWidget() histogramLayout = QHBoxLayout() histogramLayout.addWidget(self.labelHistogram) histogramLayout.addWidget(self.histogram, 1) self.probe = QVideoProbe() self.probe.videoFrameProbed.connect(self.histogram.processFrame) self.probe.setSource(self.player) openButton = QPushButton("Open", clicked=self.open) controls = PlayerControls() controls.setState(self.player.state()) controls.setVolume(self.player.volume()) controls.setMuted(controls.isMuted()) controls.play.connect(self.player.play) controls.pause.connect(self.player.pause) controls.stop.connect(self.player.stop) controls.next.connect(self.playlist.next) controls.previous.connect(self.previousClicked) controls.changeVolume.connect(self.player.setVolume) controls.changeMuting.connect(self.player.setMuted) controls.changeRate.connect(self.player.setPlaybackRate) controls.stop.connect(self.videoWidget.update) self.player.stateChanged.connect(controls.setState) self.player.volumeChanged.connect(controls.setVolume) self.player.mutedChanged.connect(controls.setMuted) self.fullScreenButton = QPushButton("FullScreen") self.fullScreenButton.setCheckable(True) self.colorButton = QPushButton("Color Options...") self.colorButton.setEnabled(False) self.colorButton.clicked.connect(self.showColorDialog) displayLayout = QHBoxLayout() displayLayout.addWidget(self.videoWidget, 2) displayLayout.addWidget(self.playlistView) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(openButton) controlLayout.addStretch(1) controlLayout.addWidget(controls) controlLayout.addStretch(1) controlLayout.addWidget(self.fullScreenButton) controlLayout.addWidget(self.colorButton) layout = QVBoxLayout() layout.addLayout(displayLayout) hLayout = QHBoxLayout() hLayout.addWidget(self.slider) hLayout.addWidget(self.labelDuration) layout.addLayout(hLayout) layout.addLayout(controlLayout) layout.addLayout(histogramLayout) self.setLayout(layout) if not self.player.isAvailable(): QMessageBox.warning(self, "Service not available", "The QMediaPlayer object does not have a valid service.\n" "Please check the media service plugins are installed.") controls.setEnabled(False) self.playlistView.setEnabled(False) openButton.setEnabled(False) self.colorButton.setEnabled(False) self.fullScreenButton.setEnabled(False) self.metaDataChanged() self.addToPlaylist(playlist) def open(self): fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files") self.addToPlaylist(fileNames) def addToPlaylist(self, fileNames): for name in fileNames: fileInfo = QFileInfo(name) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) if fileInfo.suffix().lower() == 'm3u': self.playlist.load(url) else: self.playlist.addMedia(QMediaContent(url)) else: url = QUrl(name) if url.isValid(): self.playlist.addMedia(QMediaContent(url)) def durationChanged(self, duration): duration /= 1000 self.duration = duration self.slider.setMaximum(duration) def positionChanged(self, progress): progress /= 1000 if not self.slider.isSliderDown(): self.slider.setValue(progress) self.updateDurationInfo(progress) def metaDataChanged(self): if self.player.isMetaDataAvailable(): self.setTrackInfo("%s - %s" % ( self.player.metaData(QMediaMetaData.AlbumArtist), self.player.metaData(QMediaMetaData.Title))) def previousClicked(self): # Go to the previous track if we are within the first 5 seconds of # playback. Otherwise, seek to the beginning. if self.player.position() <= 5000: self.playlist.previous() else: self.player.setPosition(0) def jump(self, index): if index.isValid(): self.playlist.setCurrentIndex(index.row()) self.player.play() def playlistPositionChanged(self, position): self.playlistView.setCurrentIndex( self.playlistModel.index(position, 0)) def seek(self, seconds): self.player.setPosition(seconds * 1000) def statusChanged(self, status): self.handleCursor(status) if status == QMediaPlayer.LoadingMedia: self.setStatusInfo("Loading...") elif status == QMediaPlayer.StalledMedia: self.setStatusInfo("Media Stalled") elif status == QMediaPlayer.EndOfMedia: QApplication.alert(self) elif status == QMediaPlayer.InvalidMedia: self.displayErrorMessage() else: self.setStatusInfo("") def handleCursor(self, status): if status in (QMediaPlayer.LoadingMedia, QMediaPlayer.BufferingMedia, QMediaPlayer.StalledMedia): self.setCursor(Qt.BusyCursor) else: self.unsetCursor() def bufferingProgress(self, progress): self.setStatusInfo("Buffering %d%" % progress) def videoAvailableChanged(self, available): if available: self.fullScreenButton.clicked.connect( self.videoWidget.setFullScreen) self.videoWidget.fullScreenChanged.connect( self.fullScreenButton.setChecked) if self.fullScreenButton.isChecked(): self.videoWidget.setFullScreen(True) else: self.fullScreenButton.clicked.disconnect( self.videoWidget.setFullScreen) self.videoWidget.fullScreenChanged.disconnect( self.fullScreenButton.setChecked) self.videoWidget.setFullScreen(False) self.colorButton.setEnabled(available) def setTrackInfo(self, info): self.trackInfo = info if self.statusInfo != "": self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo)) else: self.setWindowTitle(self.trackInfo) def setStatusInfo(self, info): self.statusInfo = info if self.statusInfo != "": self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo)) else: self.setWindowTitle(self.trackInfo) def displayErrorMessage(self): self.setStatusInfo(self.player.errorString()) def updateDurationInfo(self, currentInfo): duration = self.duration if currentInfo or duration: currentTime = QTime((currentInfo/3600)%60, (currentInfo/60)%60, currentInfo%60, (currentInfo*1000)%1000) totalTime = QTime((duration/3600)%60, (duration/60)%60, duration%60, (duration*1000)%1000); format = 'hh:mm:ss' if duration > 3600 else 'mm:ss' tStr = currentTime.toString(format) + " / " + totalTime.toString(format) else: tStr = "" self.labelDuration.setText(tStr) def showColorDialog(self): if self.colorDialog is None: brightnessSlider = QSlider(Qt.Horizontal) brightnessSlider.setRange(-100, 100) brightnessSlider.setValue(self.videoWidget.brightness()) brightnessSlider.sliderMoved.connect( self.videoWidget.setBrightness) self.videoWidget.brightnessChanged.connect( brightnessSlider.setValue) contrastSlider = QSlider(Qt.Horizontal) contrastSlider.setRange(-100, 100) contrastSlider.setValue(self.videoWidget.contrast()) contrastSlider.sliderMoved.connect(self.videoWidget.setContrast) self.videoWidget.contrastChanged.connect(contrastSlider.setValue) hueSlider = QSlider(Qt.Horizontal) hueSlider.setRange(-100, 100) hueSlider.setValue(self.videoWidget.hue()) hueSlider.sliderMoved.connect(self.videoWidget.setHue) self.videoWidget.hueChanged.connect(hueSlider.setValue) saturationSlider = QSlider(Qt.Horizontal) saturationSlider.setRange(-100, 100) saturationSlider.setValue(self.videoWidget.saturation()) saturationSlider.sliderMoved.connect( self.videoWidget.setSaturation) self.videoWidget.saturationChanged.connect( saturationSlider.setValue) layout = QFormLayout() layout.addRow("Brightness", brightnessSlider) layout.addRow("Contrast", contrastSlider) layout.addRow("Hue", hueSlider) layout.addRow("Saturation", saturationSlider) button = QPushButton("Close") layout.addRow(button) self.colorDialog = QDialog(self) self.colorDialog.setWindowTitle("Color Options") self.colorDialog.setLayout(layout) button.clicked.connect(self.colorDialog.close) self.colorDialog.show()