def __init__(self, sys_argv): super().__init__(sys_argv) # Show main window self.view = QMainWindow() self.centralWidget = QWidget(self.view) self.gridLayout = QGridLayout(self.centralWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.video_item = QVideoWidget() self.gridLayout.addWidget(self.video_item) self.view.setCentralWidget(self.centralWidget) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.grabber = VideoFrameGrabber(self.video_item, self) self.mediaPlayer.setVideoOutput(self.grabber) self.grabber.frameAvailable.connect(self.process_frame) self.mediaPlayer.durationChanged.connect(self.update_duration) self.mediaPlayer.positionChanged.connect(self.update_slider_position) local = QUrl.fromLocalFile('D:\\SampleData\\albamonSample.mp4') media = QMediaContent(local) self.mediaPlayer.setMedia(media) self.mediaPlayer.play() self.view.show()
def open_project(self, project_folder_path): """Opens a project. Args: project_folder_path: folder of the project which should be opened. """ self.project_folder_path = project_folder_path self.media_file = file_util.get_file(self.project_folder_path, c.CON_COPY_POSTFIX) if self.media_file is None: self.hide() return self.media_player.setMedia( QMediaContent(QUrl.fromLocalFile(self.media_file))) self.transcription_path = file_util.get_file(self.project_folder_path, c.TRANSCRIPTION) if self.transcription_path is None: self.hide() return with open(self.transcription_path, 'r') as f: text = f.read() self.text.setPlainText(text) self.transcription_meta_data = file_util.get_value_from_shelve( self.project_folder_path, c.TRANSCRIPTION_META_DATA) print(self.transcription_meta_data)
def precedentBouton(self): if self.ui.listWidget.count() != 0 : self.ui.listWidget.setCurrentRow((self.ui.listWidget.currentRow()-1) % self.ui.listWidget.count() ) mediaContent = QMediaContent(QUrl.fromLocalFile(self.ui.listWidget.currentItem().toolTip())) self.mediaPlayer.setMedia(mediaContent) self.lectureClicked()
def test(): url = QUrl.fromLocalFile("D:/test/1.mov") content = QMediaContent(url) player = QMediaPlayer() player.setMedia(content) # player.setVolume(Sound_level) player.play()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) #Connection du decodeur et lecteur self.mediaPlayer = QMediaPlayer() self.mediaPlayer.setVideoOutput(self.ui.ecranWidget) #chargement du media mediaContent = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi")) self.mediaPlayer.setMedia(mediaContent) #connect push boutons self.ui.pbLecture.clicked.connect(self.lectureClicked) self.ui.pbPause.clicked.connect(self.pauseClicked) self.ui.pbStop.clicked.connect(self.stopClicked) self.ui.dialVolume.valueChanged.connect(self.volControl) self.ui.nivoVolume.setText(str(self.ui.dialVolume.value())) self.ui.nivoVolume.setText('{}%'.format(str(self.ui.dialVolume.value()))) self.mediaPlayer.durationChanged.connect(self.affTemp) self.mediaPlayer.positionChanged.connect(self.avanceTemp) self.ui.barreLect.valueChanged.connect(self.avanceSlider) self.ui.pbPlus.clicked.connect(self.pbPlusCtrl) self.ui.pbMoins.clicked.connect(self.pbMoinsCtrl) self.ui.listWidget.itemDoubleClicked.connect(self.mediaSelected) self.ui.pbSuivant.clicked.connect(self.suivantBouton) self.ui.pbPrecedent.clicked.connect(self.precedentBouton)
def addMedia(self, content: QMediaContent, media_id: int) -> bool: """Append the media `content` to the playlist. Parameters ---------- content: QMediaContent The media to append. media_id: int The ID of the media in the model. Returns ------- bool Always True. """ row = self._get_row(media_id) self.mediaAboutToBeInserted.emit(row, row) self._media[media_id] = content self.mediaInserted.emit(row, row) file_name = content.canonicalUrl().fileName() log.debug(f"Added media with ID {media_id}: {file_name}") return True
def playFromURL(self): self.mediaPlayer.pause() self.myurl = self.clip.text() self.mediaPlayer.setMedia(QMediaContent(QUrl(self.myurl))) self.playButton.setEnabled(True) self.mediaPlayer.play() self.hideSlider() print(self.myurl)
def open_file(self): path, _ = QFileDialog.getOpenFileName( self, "Open file", "", "mp3 Audio (*.mp3);mp4 Video (*.mp4);Movie files (*.mov);All files (*.*)" ) if path: self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(path))) self.model.layoutChanged.emit()
def openFile(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open Movie", QDir.homePath()) if fileName != '': self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(fileName))) self.playButton.setEnabled(True)
def showEvent(self, event) -> None: if sys.platform in ['linux', 'darwin']: media_content = QMediaContent( QUrl.fromLocalFile( QFileInfo( './../example_data/sample.mp4').absoluteFilePath())) else: media_content = QMediaContent( QUrl.fromLocalFile( QFileInfo( './../example_data/pusheen.gif').absoluteFilePath())) self.media_player.setMedia(media_content) self.media_player.setVideoOutput(self.video_widget) self.video_widget.show() self.video_widget.update() self.media_player.setPosition(0) self.media_player.play()
def load(self, file_url: QUrl): if file_url is None: return None if file_url.isValid(): c = QMediaContent(file_url) self.player.setMedia(c) self.media_loaded.emit(self.playlist.current_title()) self.enableInterface()
def test2(): url = QUrl.fromLocalFile("D:/test/2.mp4") content = QMediaContent(url) player = QMediaPlayer() vw = QVideoWidget() vw.show() player.play() player.setVideoOutput(vw) player.setMedia(content)
def loadfile(self): #rowItem=self.ui.file_list.currentRow() currentItem = self.ui.file_list.currentItem() print(self.ui.file_list.currentItem().text()) #mediaContent=QMediaContent(QUrl.fromLocalFile(currentItem.toolTip())) mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.text())) #mediaContent = QMediaContent(QUrl.fromLocalFile('big_buck_bunny.avi')) self.mediaPlayer.setMedia(mediaContent) self.PLAY()
def dropEvent(self, e): for url in e.mimeData().urls(): self.playlist.addMedia(QMediaContent(url)) self.model.layoutChanged.emit() # If not playing, seeking to first of newly added + play. if self.player.state() != QMediaPlayer.PlayingState: i = self.playlist.mediaCount() - len(e.mimeData().urls()) self.playlist.setCurrentIndex(i) self.player.play()
def searchButton(self): entry = self.searchText.text() model = self.listView.model() for index in range(self.playlist.mediaCount()): item = self.playlist.media(index).canonicalUrl().fileName() if entry in item.lower(): self.playlist.clear() # self.model.beginResetModel() self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(item))) self.model.layoutChanged.emit()
def resetPlayList(self, list_of_titles: List[Title]): self.__playlist.clear() for t in list_of_titles: url = t.link video = pafy.new(url) best = video.getbest() self.__playlist.addMedia(QMediaContent(QUrl(best.url))) self.__playlist.setCurrentIndex(0) self.__player.setPlaylist(self.__playlist)
def add_media_triggered(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog files, _ = QFileDialog.getOpenFileNames(None, "Select Media Files", "", "All Files (*)", options=options) if files: for file in files: self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(file))) self.playlistDisplay.addItem(os.path.basename(file))
def play(self): self.finished = 0 path = '%s/%s' % (self.save_dir, self.options['uri']) self.playlist.addMedia(QMediaContent(path)) self.player.play() self.widget.show() self.widget.raise_() if float(self.duration) > 0: self.play_timer.setInterval(int(float(self.duration) * 1000)) self.play_timer.start() self.started_signal.emit()
def _populate(self): """Populate the playlist with existing media in the model.""" for row in range(self._model.rowCount()): path = self._model.index(row, 7).data() if Path(path).is_file(): media = QMediaContent(QUrl.fromLocalFile(path)) media_id = self._get_media_id(row) self.addMedia(media, media_id) else: # TODO: Prompt user to remove from model on failure log.warning(f"Could not populate playlist for row {row}: " f"{path} does not exist or isn't a file.")
def browseFile(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.play.setIcon(self.playIcon) self.mediaPlayer.pause() elif self.mediaPlayer.state() == QMediaPlayer.PausedState: self.play.setIcon(self.pauseIcon) self.mediaPlayer.play() elif not (self.playlist.isEmpty()): self.mediaPlayer.setPlaylist(self.playlist) self.mediaPlayer.play() self.play.setIcon(self.pauseIcon) else: media, _ = QFileDialog.getOpenFileName(self, "Open Video") if media != "": self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(media))) self.playlist.addMedia(QMediaContent( QUrl.fromLocalFile(media))) self.mediaPlayer.play() self.play.setIcon(self.pauseIcon)
def start_play_item(self, index): i = index.row() if self.player.state() == QMediaPlayer.PlayingState: self.player.stop() self.begin_seek = False self.play_url = self.items[i]['url'] self.media = QMediaContent(self.items[i]['url']) self.player.setMedia(self.media) self.player.play() self.widget.set_duration(self.items[i]['duration'])
def PREV(self): print('PREV PRESSED') rowItem = self.ui.file_list.currentRow() if rowItem == -1: return else: self.ui.file_list.setCurrentRow((rowItem - 1)) filename = self.ui.file_list.currentItem().text() print('Loading ' + filename) mediaContent = QMediaContent(QUrl.fromLocalFile(filename)) self.mediaPlayer.setMedia(mediaContent) self.PLAY()
def mediaChanged(self, media: QtMultimedia.QMediaContent): # print(media, vars(media), dir(media)) raw_path = media.canonicalUrl().toString() if raw_path.strip() != "": print(f"{raw_path=}") probe = FFProbe(raw_path) for k, v in probe.info.items(): print(f"\t{k}: {v}") self.view.progress_bar.setRange(0, probe.duration_ms) self.view.current_song.setText( f"{probe.listing} ({probe.duration_str})")
def vedio_show(self, vedio_dir=None): if vedio_dir: #添加播放文件 self.media_content = QMediaContent(QUrl.fromLocalFile(vedio_dir)) self.player.setMedia(self.media_content) #声音 self.player.setVolume(50) #开始播放 self.player.play() else: QMessageBox.critical(self,'文件打开失败',\ '1.文件扩展名与文件类型不匹配!\n2.路径中请勿含有中文字符!\n3.文件损坏!\n4.文件无法读取!') exit(-1)
def dropEvent(self, event): print("drop") if event.mimeData().hasUrls(): url = event.mimeData().urls()[0].toString() print("url = ", url) self.mediaPlayer.stop() self.mediaPlayer.setMedia(QMediaContent(QUrl(url))) self.playButton.setEnabled(True) self.mediaPlayer.play() elif event.mimeData().hasText(): mydrop = event.mimeData().text() ### YouTube url if "youtube" in mydrop: print("is YouTube", mydrop) self.clip.setText(mydrop) self.getYTUrl() else: ### normal url print("generic url = ", mydrop) self.mediaPlayer.setMedia(QMediaContent(QUrl(mydrop))) self.playButton.setEnabled(True) self.mediaPlayer.play() self.hideSlider()
def NEXT(self): print('NEXT PRESSED') totalItems = self.ui.file_list.count() rowItem = self.ui.file_list.currentRow() if rowItem + 1 > totalItems: return else: self.ui.file_list.setCurrentRow((rowItem + 1)) filename = self.ui.file_list.currentItem().text() print('Loading ' + filename) mediaContent = QMediaContent(QUrl.fromLocalFile(filename)) self.mediaPlayer.setMedia(mediaContent) self.PLAY()
def setMedia(self, media: QtMultimedia.QMediaContent, stream: QtCore.QIODevice = None, realDuration=None) -> None: self.blockSignals(True) super().setMedia(media, stream) self.blockSignals(False) self._realDuration = realDuration self._lastFakePosition = 0 self._bugRate = 0.0 if realDuration is None: filename = media.canonicalUrl().toLocalFile() file = taglib.File(filename) bitrate = file.bitrate file.close() self._realDuration = Path(filename).stat().st_size * 8 // bitrate
def __init__(self, url): # type: (str) -> None self.__url = url # Only used for debugging # Tell the app not to quit while this sound is loading, since it is plausible that a user is using sounds # without using a frame or any timers: TheApp.add_tracked(self) self.__player = QMediaPlayer(TheApp, flags=QMediaPlayer.LowLatency) self.__player.setAudioRole(QAudio.GameRole) self.__player.mediaStatusChanged.connect(self.__on_status_changed) self.__player.error.connect(self.__on_status_changed) req = request(url) content = QMediaContent(req) self.__player.setMedia(content) self.__sound_loaded = False self.__play_requested = False
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pbPlay.clicked.connect(self.lectureClicked) self.ui.pbPause.clicked.connect(self.pauseClicked) self.ui.pbStop.clicked.connect(self.stopClicked) self.ui.pbNext.clicked.connect(self.nextClicked) self.ui.pbPrevious.clicked.connect(self.previousClicked) self.ui.pbAdd.clicked.connect(self.addClicked) self.ui.pbDelete.clicked.connect(self.deleteClicked) self.ui.dVolume.valueChanged.connect(self.volume) self.mediaPlayer = QMediaPlayer() self.mediaPlayer.setVideoOutput(self.ui.wLecteur) self.mediaPlayer.durationChanged.connect(self.mediaDurationCnahged) self.mediaPlayer.positionChanged.connect(self.mediaPositionCnahged) self.ui.wList.itemDoubleClicked.connect(self.mediaSelected) mediaContent = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi")) self.mediaPlayer.setMedia(mediaContent)
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pblecture.clicked.connect(self.lectureClicked) self.ui.pbpause.clicked.connect(self.pauseClicked) self.ui.pbstop.clicked.connect(self.stopClicked) self.ui.pbmoins.clicked.connect(self.supprMedia) self.ui.pbplus.clicked.connect(self.ajouterMedia) self.ui.pbprecedent.clicked.connect(self.precedentClicked) self.ui.pbsuivant.clicked.connect(self.suivantClicked) self.mediaPlayer = QMediaPlayer() #creation de la variable mediaPlayer self.mediaPlayer.setVideoOutput( self.ui.ecran) #on projette la var mediaPlayer sur ecran. self.ui.dialVolume.valueChanged.connect(self.volumeChanged) self.mediaPlayer.durationChanged.connect(self.mediaDurationChanged) self.mediaPlayer.positionChanged.connect(self.mediaPositionChanged) self.ui.listWidget.itemDoubleClicked.connect(self.mediaSelected) # Commande qui permet de lancer le film (depuis le début) mediaContent = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi")) self.mediaPlayer.setMedia(mediaContent)