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)))
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 MediaPlayer(metaclass=Observable): class Error(Enum): none = QMediaPlayer.NoError unsupported_format = QMediaPlayer.FormatError access_denied = QMediaPlayer.AccessDeniedError closed = signal() playing = signal(Track) stopped = signal(Track) error_occurred = signal(Track) def __init__(self): self._media_library = create_media_library() self._playlist = [] self._player = QMediaPlayer() self._player.stateChanged.connect(self._state_changed) self._player.mediaStatusChanged.connect(self._media_status_changed) def play(self, track): self._playlist.append(track) self._player.setMedia(self._media_library.fetch(track.filename)) self._player.play() def stop(self): self._player.stop() def _media_status_changed(self, state): if state == QMediaPlayer.BufferedMedia: self._error = QMediaPlayer.NoError self.playing.emit(self._playlist[0]) elif state == QMediaPlayer.InvalidMedia: # On windows 8, we only get an InvalidMedia status in case of error, # so we need to keep track of the error that occurred self._error = QMediaPlayer.FormatError @property def error(self): return MediaPlayer.Error(self._player.error() or self._error) def _state_changed(self, state): if state == QMediaPlayer.StoppedState and self.error is not MediaPlayer.Error.none: self.error_occurred.emit(self._playlist.pop(0), self.error) elif state == QMediaPlayer.StoppedState: self.stopped.emit(self._playlist.pop(0)) def dispose(self): self._player.stop() # force the deletion of the player on windows because windows # doesn't release the handle and prevents further instanciations sip.delete(self._player) self._player = None self._media_library.dispose() self.closed.emit()
class Window(QWidget): """ The main window of the application. Houses a media player and related controls. """ def __init__(self): super().__init__() layout = QVBoxLayout() self.slider = QSlider(Qt.Horizontal) btnOpen = QPushButton("Open") btnPlay = QPushButton("Play") self.player = QMediaPlayer() tl = Timeline(None, None) tlscroll = QScrollArea() tlscroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) tlscroll.setWidget(tl) btnOpen.clicked.connect(self.open) btnPlay.clicked.connect(self.play) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) layout.addWidget(self.slider) layout.addWidget(btnOpen) layout.addWidget(btnPlay) layout.addWidget(tlscroll) self.setLayout(layout) def open(self): fileName = QFileDialog.getOpenFileName(self, "Open File")[0] fileInfo = QFileInfo(fileName) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) self.changeMedia(QMediaContent(url)) def play(self): self.player.play() def changeMedia(self, mediaContent): self.player.setMedia(mediaContent) def durationChanged(self, duration): self.slider.setRange(0, duration) def positionChanged(self, position): self.slider.setValue(position)
def __init__(self, video, parent=None): super(Video, self).__init__(parent) self.ui = Ui_Video() self.ui.setupUi(self) self.video = video self.setWindowTitle("Video - %s" % video.title) self.ui.urlEdit.setText(video.url) self.ui.titleLabel.setText(video.title) self.ui.durationLabel.setText(unicode(video.duration)) self.ui.authorLabel.setText(unicode(video.author)) self.ui.dateLabel.setText(unicode(video.date)) if video.rating_max: self.ui.ratingLabel.setText('%s / %s' % (video.rating, video.rating_max)) else: self.ui.ratingLabel.setText('%s' % video.rating) self.mediaPlayer = QMediaPlayer() self.mediaPlayer.durationChanged.connect(self._setMax) self.mediaPlayer.seekableChanged.connect(self.ui.seekSlider.setEnabled) self.mediaPlayer.positionChanged.connect(self._slide) self.ui.seekSlider.valueChanged.connect(self.mediaPlayer.setPosition) mc = QMediaContent(QUrl(video.url)) self.mediaPlayer.setMedia(mc) self.ui.videoPlayer.setMediaObject(self.mediaPlayer) self.mediaPlayer.play()
def __init__(self,projectfile,MainWidget): QtWidgets.QWidget.__init__(self) self.setupUi(self) self.setWindowFlags(Qt.WindowStaysOnTopHint) self.Main = MainWidget self.iface = self.Main.iface self.muteButton.setIcon( self.style().standardIcon(QStyle.SP_MediaVolume)) self.replayPlay_pushButton.setIcon( self.style().standardIcon(QStyle.SP_MediaPlay)) if projectfile.split('.')[-1] =="vgp": self.projectfile = projectfile else: self.projectfile = projectfile +'.vgp' self.videofile = None self.GPXfile = None self.GPXList = None self.fps = None self.RealFps = None self.DB = None self.player = QMediaPlayer() self.player.setVideoOutput(self.video_frame_2) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.stateChanged.connect(self.mediaStateChanged) self.toolButton_3.clicked.connect(self.ManageDB) self.pushButton_2.clicked.connect(self.Synchronize) self.pushButton.clicked.connect(self.SelectVideoGPX) self.replayPlay_pushButton.clicked.connect(self.PlayPause) self.muteButton.clicked.connect(self.MuteUnmute) self.horizontalSlider.sliderMoved.connect(self.setPosition) self.toolButton.clicked.connect(self.SkipBackward) self.toolButton_2.clicked.connect(self.SkipForward) self.SkipBacktoolButton_7.clicked.connect(self.BackwardFrame) self.SkipFortoolButton_8.clicked.connect(self.ForwardFrame)
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 __init__(self, parent=None): super(GameWindow, self).__init__(parent) self.media_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.video_widget = QVideoWidget() self.video_widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.media_player.setVideoOutput(self.video_widget) self.string_label = QLabel() self.string_label.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.string_label.setTextFormat(Qt.RichText) self.string_label.setAlignment(Qt.AlignHCenter) self.string_label.setWordWrap(1) layout = QVBoxLayout() layout.addWidget(self.video_widget) layout.addWidget(self.string_label) self.setLayout(layout) self.media_player.positionChanged.connect(self.position_changed) self.resize(640, 480) self.setWindowTitle("Game")
def __init__(self): super(VideoSortApp, self).__init__() self.setupUi(self) self.filename = None self.directory = None self.sort.setEnabled(False) self.fileOpen.clicked.connect(self.fileDialog) self.dirOpen.clicked.connect(self.folderDialog) self.sort.clicked.connect(self.sortVideo) self.results.setViewMode(self.results.IconMode) self.results.setResizeMode(self.results.Adjust) self.features = [] self.sorted = None #player properties self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.playlist = QMediaPlaylist(self.player) self.videoItem = QGraphicsVideoItem() self.videoItem.setSize(QtCore.QSizeF(640, 480)) scene = QGraphicsScene(self) scene.addItem(self.videoItem) self.graphicsView.setScene(scene) self.player.setVideoOutput(self.videoItem) self.graphicsView.resize(640,480) self.graphicsView.show() self.results.itemDoubleClicked.connect(self.seekVideo) self.videoLoaded = False
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, parent=None, display_status=False): super(VideoPlayer, self).__init__(parent) self.display_status = display_status self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.videoItem = QGraphicsVideoItem() scene = QGraphicsScene(self) graphicsView = QGraphicsView(scene) scene.addItem(self.videoItem) self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.setPosition) if self.display_status: self.status_mapping = { QMediaPlayer.UnknownMediaStatus: "UnknownMediaStatus", QMediaPlayer.NoMedia: "NoMedia", QMediaPlayer.LoadingMedia: "LoadingMedia", QMediaPlayer.LoadedMedia: "LoadedMedia", QMediaPlayer.StalledMedia: "StalledMedia", QMediaPlayer.BufferingMedia: "BufferingMedia", QMediaPlayer.BufferedMedia: "BufferedMedia", QMediaPlayer.EndOfMedia: "EndOfMedia", QMediaPlayer.InvalidMedia: "InvalidMedia" } self.statusText = QPlainTextEdit() self.statusText.setReadOnly(True) self.statusText.setFixedHeight(25) self.statusText.setFixedWidth(150) self.mediaPlayer.mediaStatusChanged.connect(self.mediaStatusChanged) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.positionSlider) if self.display_status: controlLayout.addWidget(self.statusText) layout = QVBoxLayout() layout.addWidget(graphicsView) layout.addLayout(controlLayout) self.setFixedWidth(WIDTH + WIGGLE) self.setLayout(layout) self.mediaPlayer.setVideoOutput(self.videoItem) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.durationChanged.connect(self.durationChanged)
def __init__(self, parent=None): super(Speaker,self).__init__(parent) self.player = QMediaPlayer(self) try: self.backup = steel.available_engines()[0]() self.backup.set("rate", 150) except: self.backup = None print("Could not start a backup offline speaker.")
def _set_media(self, movie: Movie): if self.media_player is None: self.media_player = QMediaPlayer(self.videoArea, QMediaPlayer.VideoSurface) self.media_player.setVideoOutput(self.videoArea.videoSurface()) self._connect_player_signals() file_name = movie.get_target_path() mimetype = mimetypes.guess_type(file_name)[0] logger.debug("Found mimetype: {}".format(mimetype)) media_res = QMediaResource(QUrl.fromLocalFile(file_name), mimetype) media = QMediaContent(media_res) self.media_player.setMedia(media)
def __init__(self, file_name=None): """Set up a Signal object with the given file (or none by default). Args: file_name (str): File path of the file to open. Only .wav files permitted. """ super().__init__() self.file_name = None self.waveform_data = None self.waveform_info = None self.media_player = QMediaPlayer() self.open(file_name)
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, playList = [], ddir = "data", parent = None): """ @param dfile: 萝莉的音乐配置文件 """ QMediaPlayer.__init__(self, parent) # super(LolitaMusic, 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 __init__(self, view, log): self.log = log self.view = view self._player = QMediaPlayer() self._player.mediaStatusChanged.connect(self._player_status_changed) self._player.mediaChanged.connect(self._player_media_changed) self._player.currentMediaChanged.connect(self._player_current_media_changed) self._player.stateChanged.connect(self._player_state_changed) self._player.positionChanged.connect(self._player_position_changed) self._player.durationChanged.connect(self._player_duration_changed) self._searched_tracks = [] self.playlists = [] self.playing_playlist = 0 self.last_colored_item = None
class Video(QDialog): def __init__(self, video, parent=None): super(Video, self).__init__(parent) self.ui = Ui_Video() self.ui.setupUi(self) self.video = video self.setWindowTitle("Video - %s" % video.title) self.ui.urlEdit.setText(video.url) self.ui.titleLabel.setText(video.title) self.ui.durationLabel.setText(unicode(video.duration)) self.ui.authorLabel.setText(unicode(video.author)) self.ui.dateLabel.setText(unicode(video.date)) if video.rating_max: self.ui.ratingLabel.setText('%s / %s' % (video.rating, video.rating_max)) else: self.ui.ratingLabel.setText('%s' % video.rating) self.mediaPlayer = QMediaPlayer() self.mediaPlayer.durationChanged.connect(self._setMax) self.mediaPlayer.seekableChanged.connect(self.ui.seekSlider.setEnabled) self.mediaPlayer.positionChanged.connect(self._slide) self.ui.seekSlider.valueChanged.connect(self.mediaPlayer.setPosition) mc = QMediaContent(QUrl(video.url)) self.mediaPlayer.setMedia(mc) self.ui.videoPlayer.setMediaObject(self.mediaPlayer) self.mediaPlayer.play() @Slot('qint64') def _slide(self, pos): blocking = self.ui.seekSlider.blockSignals(True) self.ui.seekSlider.setValue(pos) self.ui.seekSlider.blockSignals(blocking) @Slot('qint64') def _setMax(self, duration): self.ui.seekSlider.setMaximum(duration) def closeEvent(self, event): self.mediaPlayer.stop() event.accept() def hideEvent(self, event): self.mediaPlayer.stop() event.accept()
def __init__(self, parent=None): super().__init__() self.parent = parent self.player = QMediaPlayer() self.player.setVolume(int(settings().value("Player/volume") or 100)) self.player.setVideoOutput(self) self.timer = QTimer(self) self.timer.timeout.connect(self.timerPos) self.player.currentMediaChanged.connect(self.signalStart) self.player.currentMediaChanged.connect(self.parent.subtitleitem.subtitleControl) self.player.currentMediaChanged.connect(self.videoConfigure) """self.player.mediaStatusChanged.connect(self.metadata)
def __init__(self, parent=None): super(VideoPlayer, self).__init__(parent) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.videoItem = QGraphicsVideoItem() self.videoItem.setSize(QSizeF(640, 480)) scene = QGraphicsScene(self) graphicsView = QGraphicsView(scene) scene.addItem(self.videoItem) rotateSlider = QSlider(Qt.Horizontal) rotateSlider.setRange(-180, 180) rotateSlider.setValue(0) rotateSlider.valueChanged.connect(self.rotateVideo) openButton = QPushButton("Open...") openButton.clicked.connect(self.openFile) self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.setPosition) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(openButton) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.positionSlider) layout = QVBoxLayout() layout.addWidget(graphicsView) layout.addWidget(rotateSlider) layout.addLayout(controlLayout) self.setLayout(layout) self.mediaPlayer.setVideoOutput(self.videoItem) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.durationChanged.connect(self.durationChanged)
def main(): app = QApplication(sys.argv) # Create media player, read media URL from first command line argument player = QMediaPlayer() media = QMediaContent(QUrl(sys.argv[1])) player.setMedia(media) # Create and set video output widget video = QVideoWidget() player.setVideoOutput(video) video.show() player.play() sys.exit(app.exec_())
def __init__(self, playlist=''): super().__init__() self.player = QMediaPlayer() self.wrapper = PlaylistWrapper("Untitled") self.playlist = self.wrapper.playlist self.player.setPlaylist(self.playlist) browseButton = QPushButton("Browse", clicked=self.crawl) saveButton = QPushButton("Save", clicked=self.save) loadButton = QPushButton("Load", clicked=self.load) addButton = QPushButton("Add song", clicked=self.add_song) nameButton = QPushButton("Name", clicked=self.name_playlist) controls = PlayerControls() 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.playlist.previous) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(browseButton) controlLayout.addWidget(saveButton) controlLayout.addWidget(loadButton) controlLayout.addWidget(addButton) controlLayout.addWidget(nameButton) controlLayout.addStretch(1) controlLayout.addWidget(controls) controlLayout.addStretch(1) self.displayLayout = QHBoxLayout() self.playlist_view = QListWidget() self.displayLayout.addWidget(self.playlist_view) self.layout = QVBoxLayout() self.layout.addLayout(self.displayLayout) self.layout.addLayout(controlLayout) self.layout.addLayout(self.displayLayout) self.setLayout(self.layout) self.setWindowTitle( "letTheMusicPlaY - {} Playlist".format(self.wrapper.name))
def __init__(self, parent=None): super(VideoPlayer, self).__init__(parent) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) videoWidget = QVideoWidget() openButton = QPushButton("Open...") openButton.clicked.connect(self.openFile) self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.setPosition) self.errorLabel = QLabel() self.errorLabel.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(openButton) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.positionSlider) layout = QVBoxLayout() layout.addWidget(videoWidget) layout.addLayout(controlLayout) layout.addWidget(self.errorLabel) self.setLayout(layout) self.mediaPlayer.setVideoOutput(videoWidget) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.durationChanged.connect(self.durationChanged) self.mediaPlayer.error.connect(self.handleError)
def __init__(self, parent=None): super(GameWindow,self).__init__(parent) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.videoWidget = QVideoWidget() self.mediaPlayer.setVideoOutput(self.videoWidget) self.stringLabel = QLabel() self.stringLabel.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) self.stringLabel.setTextFormat(Qt.RichText) self.stringLabel.setAlignment(Qt.AlignHCenter) layout = QVBoxLayout() layout.addWidget(self.videoWidget) layout.addWidget(self.stringLabel) self.setLayout(layout) self.mediaPlayer.positionChanged.connect(self.positionChanged)
def __init__(self): #self.parent = parent self.isLoop = 0 #0循环列表,1单曲循环 self.isRandom = 0 #0不随机,1随机 self.fileList = [] #曲目名称列表 self.randomList =[] #播放列表 self.soundID = 0 #当前歌曲ID self.playStat = False #当前播放状态 (0未播放,1播放) self.openPath = "F:/mp3/" #歌曲目录 self.isPreview = 0 #试用开关,0正常播放,1列表中的歌曲每首歌曲放10秒 self.currentVolume = 0.1#默认的起始音量 self.isInitPlay = 1 #是否是初始播放 #==>>打开目录 self.config=configparser.ConfigParser() self.config.read('config.ini') self.openDir() #打开目录<<== self.playObj = QMediaPlayer() self.currentImg = "" #当前图片 self.songText = {} #歌词 self.songTextKey=[] #歌词KEY
def __init__(self, parent=None): super(VideoPlayerWidget, self).__init__(parent) self.scene = QGraphicsScene(self) self.scene.setBackgroundBrush(QBrush(QColor(0, 0, 0, 255))) self.graphics_view = QGraphicsView(self.scene) self.graphics_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setFrameStyle(0) self.graphics_view.setStyleSheet("QGraphicsView {background: transparent; border: 3px; outline: none;}") self.video_item = QGraphicsVideoItem() self.scene.addItem(self.video_item) self.layout = QVBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.addWidget(self.graphics_view) self.media_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.media_player.setVideoOutput(self.video_item) self.video_need_replay = False self.video_seek_durcation = 3000 # in milliseconds
def __init__(self): super(PlayWindow, self).__init__() self.media_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.video_widget = QVideoWidget() self.play_button = QPushButton() self.play_button.setEnabled(False) self.play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.play_button.clicked.connect(self.play) self.position_slider = QSlider(Qt.Horizontal) self.position_slider.setRange(0, 0) self.position_slider.sliderMoved.connect(self.set_position) self.error_label = QLabel() self.error_label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) self.control_layout = QHBoxLayout() self.control_layout.setContentsMargins(0, 0, 0, 0) self.control_layout.addWidget(self.play_button) self.control_layout.addWidget(self.position_slider) self.layout = QVBoxLayout() self.layout.addWidget(self.video_widget) self.layout.addLayout(self.control_layout) self.layout.addWidget(self.error_label) self.setLayout(self.layout) self.media_player.setVideoOutput(self.video_widget) self.media_player.stateChanged.connect(self.media_state_changed) self.media_player.positionChanged.connect(self.position_changed) self.media_player.durationChanged.connect(self.duration_changed) self.media_player.error.connect(self.handle_error) self.resize(640, 480) self.setWindowTitle("Preview")
def __init__(self, volumeLevel=40, playbackMode=QMediaPlaylist.Sequential, parent=None): super(AudioPlayer, self).__init__(parent) self.__player = QMediaPlayer() self.__player.setVolume(volumeLevel) self.__player.currentMediaChanged.connect(self._onMediaChanged) self.__player.stateChanged.connect( lambda state: self.stateChanged.emit(int(state))) self.__player.positionChanged.connect( lambda x: self.songPositionChanged.emit(x)) self.__player.durationChanged.connect( lambda x: self.songDurationChanged.emit(x)) self.__playlistManager = PlaylistManger() self.__playlistManager.customPlaylistCreated.connect( lambda uuid, name: self.customPlaylistCreated.emit(uuid, name)) self.__playlistManager.libraryPlaylistCreated.connect( lambda p: self.libraryPlaylistCreated.emit(p)) self.__playlistManager.currentPlaylistChanged.connect( self._onChangedPlaylist) self.__playlistManager.currentPlaylistChanged.connect( lambda p, i: self.playlistChanged.emit(p, i)) self.__playlistManager.playlistRemoved.connect( lambda uuid: self.playlistRemoved.emit(uuid)) self.__playlistManager.addedToLibraryPlaylist.connect( lambda uuid, l: self.addedToLibraryPlaylist.emit(uuid, l)) self.__playlistManager.addedToCustomPlaylist.connect( lambda uuid, l: self.addedToCustomPlaylist.emit(uuid, l)) self.__playlistManager.updatedLibraryPlaylist.connect( lambda uuid, l: self.updatedLibraryPlaylist.emit(uuid, l))
def __init__(self): super().__init__() layout = QVBoxLayout() self.slider = QSlider(Qt.Horizontal) btnOpen = QPushButton("Open") btnPlay = QPushButton("Play") self.player = QMediaPlayer() tl = Timeline(None, None) tlscroll = QScrollArea() tlscroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) tlscroll.setWidget(tl) btnOpen.clicked.connect(self.open) btnPlay.clicked.connect(self.play) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) layout.addWidget(self.slider) layout.addWidget(btnOpen) layout.addWidget(btnPlay) layout.addWidget(tlscroll) self.setLayout(layout)
class Speaker(QObject): def __init__(self, parent=None): super(Speaker,self).__init__(parent) self.player = QMediaPlayer(self) try: self.backup = steel.available_engines()[0]() self.backup.set("rate", 150) except: self.backup = None print("Could not start a backup offline speaker.") @pyqtSlot(str, str) def speak(self, name, text, lang="pt-br"): fpath = "./speeches/" + name + ".mp3" if not os.path.isdir("./speeches"): os.mkdir("./speeches") if not os.path.isfile(fpath): print("Running TTS...") try: data = urlencode( [("tl", lang), ("q", text), ("ie", "UTF-8")] ) bin_data = data.encode("utf8") req = Request("http://translate.google.com/translate_tts", bin_data, {"User-Agent":"My agent !"}) fin = urlopen(req) mp3 = fin.read() fout = open(fpath, "wb") fout.write(mp3) fout.close() except Exception as exc: print("Error trying to get TTS file:", str(exc)) if self.backup != None: print("Proceeding to use backup speaker...") self.backup.speak(text) return self.player.stop() self.player.setMedia(QMediaContent(QUrl.fromLocalFile(QFileInfo(fpath).absoluteFilePath()))) self.player.play()
class Video(QMainWindow): def __init__(self, parent=None): super(Video, self).__init__(parent) self.setWindowTitle("Video Editor") self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) videoWidget = QVideoWidget() self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.setPosition) self.errorLabel = QLabel() self.errorLabel.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) # Upload video openAction = QAction(QIcon('open.png'), '&Open', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Open movie') openAction.triggered.connect(self.openFile) # Exit video exitAction = QAction(QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.exitCall) # Menu bar and add action menuBar = self.menuBar() fileMenu = menuBar.addMenu('&File') fileMenu.addAction(openAction) fileMenu.addAction(exitAction) # Window content wid = QWidget(self) self.setCentralWidget(wid) # Layouts for widget controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.positionSlider) layout = QVBoxLayout() layout.addWidget(videoWidget) layout.addLayout(controlLayout) layout.addWidget(self.errorLabel) wid.setLayout(layout) self.mediaPlayer.setVideoOutput(videoWidget) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.durationChanged.connect(self.durationChanged) self.mediaPlayer.error.connect(self.handleError) 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 exitCall(self): sys.exit(app.exec_()) def play(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() def mediaStateChanged(self, state): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playButton.setIcon(self.style().standardIcon( QStyle.SP_MediaPause)) else: self.playButton.setIcon(self.style().standardIcon( QStyle.SP_MediaPlay)) def positionChanged(self, position): self.positionSlider.setValue(position) def durationChanged(self, duration): self.positionSlider.setRange(0, duration) def setPosition(self, position): self.mediaPlayer.setPosition(position) def handleError(self): self.playButton.setEnabled(False) self.errorLabel.setText("Error: " + self.mediaPlayer.errorString())
class VideoPlayerWidget(QWidget): def __init__(self, parent=None): super(VideoPlayerWidget, self).__init__(parent) self.scene = QGraphicsScene(self) self.scene.setBackgroundBrush(QBrush(QColor(0, 0, 0, 255))) self.graphics_view = QGraphicsView(self.scene) self.graphics_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.graphics_view.setFrameStyle(0) self.graphics_view.setStyleSheet( "QGraphicsView {background: transparent; border: 3px; outline: none;}" ) self.video_item = QGraphicsVideoItem() self.scene.addItem(self.video_item) self.layout = QVBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.addWidget(self.graphics_view) self.media_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.media_player.setVideoOutput(self.video_item) self.video_need_replay = False self.video_seek_durcation = 3000 # in milliseconds def resizeEvent(self, event): self.video_item.setSize( QSizeF(event.size().width(), event.size().height())) QWidget.resizeEvent(self, event) def play(self, url): self.media_player.setMedia(QMediaContent(QUrl.fromLocalFile(url))) self.media_player.play() def seek_forward(self): video_position = self.media_player.position() self.media_player.setPosition(video_position + self.video_seek_durcation) def seek_backward(self): video_position = self.media_player.position() self.media_player.setPosition( max(video_position - self.video_seek_durcation, 0))
class InputManager: __instance = None def __init__(self): if not InputManager.__instance: self.ui_manager = UIManager.get_instance() self.radio_stations_manager = RadioStationsManager() self.player = None self.playlist = None self.probe = None self.load_state() if not self.playlist: self.init_state() self.init_signals() def init_signals(self): self.player.durationChanged.connect(self.duration_changed_slot) self.player.positionChanged.connect(self.position_changed_slot) self.player.currentMediaChanged.connect( self.current_media_changed_slot) self.player.stateChanged.connect(self.state_changed_slot) def set_position(self, new_pos): self.ui_manager.set_position_slider_value(new_pos) self.player.setPosition(new_pos) def get_duration(self): return self.player.duration() def get_position(self): return self.player.position() def duration_changed_slot(self, duration): self.ui_manager.set_position_slider_max_value(duration) def position_changed_slot(self, position): self.ui_manager.set_position_slider_value(position) def get_volume(self): return self.player.volume() def set_volume(self, value): self.ui_manager.set_volume_slider_value(value) self.player.setVolume(value) def current_media_changed_slot(self): self.ui_manager.sync_row(self.get_media_position()) def state_changed_slot(self, new_state): if new_state == QMediaPlayer.StoppedState or new_state == QMediaPlayer.PausedState: self.ui_manager.change_play_btn_state(False) else: self.ui_manager.change_play_btn_state(True) def next_media(self): self.playlist.next() def previous_media(self): self.playlist.previous() @classmethod def get_instance(cls, *args, **kwargs): if not cls.__instance: cls.__instance = InputManager(*args, **kwargs) return cls.__instance def init_state(self): self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.probe = QAudioProbe() self.probe.setSource(self.player) self.probe_connected = False self.timer = QTimer() self.timer.setInterval(100) self.timer.setSingleShot(True) self.recent_files_manager = RecentFilesManager() self.ui_manager.set_output(self.player) self.player.setPlaylist(self.playlist) def load_state(self): file = QFile("file.dat") file.open(QIODevice.ReadOnly) in_stream = QDataStream(file) cur_playlist = QVariant() in_stream >> cur_playlist self.playlist = cur_playlist.value() def get_radio_stations(self, limit=None, category=None): stations = self.radio_stations_manager.get_all_stations( limit, category) return stations def get_radio_categories(self): categories = self.radio_stations_manager.get_all_categories() return categories def save_state(self): file = QFile("file.dat") file.open(QIODevice.WriteOnly) out = QDataStream(file) out << QVariant(self.current_playlist) def add_folder(self, path: str): files = get_dir_files(path) for file in files: self.add_media(path + "/" + file, get_format(file)) def add_file(self, filename: str): format = get_format(filename) if format != FILE_FORMAT.INVALID: return self.add_media(filename, format) raise RuntimeError("Invalid file format") def add_media(self, filename: str, format: FILE_FORMAT): url = QUrl.fromLocalFile( filename) if format != FILE_FORMAT.URL else QUrl(filename) content = QMediaContent(url) self.ui_manager.append_playlist(url.fileName(), format) self.recent_files_manager.write_recent_file(url.path()) self.ui_manager.init_recent_files() self.playlist.addMedia(content) def set_media_position(self, pos): self.playlist.setCurrentIndex(pos) def get_media_position(self): return self.playlist.currentIndex() def get_current_format(self): position = self.get_media_position() if position == -1: return None item = self.ui_manager.get_list_item(self.get_media_position()) return item.data(PlaylistItemDataRole.FORMAT) def play(self): format = self.get_current_format() if format is None: return self.ui_manager.change_play_btn_state(True) if format == FILE_FORMAT.AUDIO: self.probe.audioBufferProbed.connect(self.process_buffer) self.probe_connected = True else: self.probe_connected = False self.ui_manager.show_video() self.player.play() def pause(self): self.player.pause() def stop(self): self.player.stop() def is_muted(self): return self.player.isMuted() def is_paused(self): return self.player.state() in (QMediaPlayer.StoppedState, QMediaPlayer.PausedState) def mute(self, toggle): self.ui_manager.change_mute_state(toggle, self.get_volume()) self.player.setMuted(toggle) def get_playback_rate(self): return self.player.playbackRate() def set_playback_rate(self, value): self.player.setPlaybackRate(value) def process_buffer(self, buffer): if not self.probe_connected: return if not self.timer.isActive(): self.timer.start() else: if self.timer.remainingTime() == 0: data = buffer.data() chunked = chunk(list(data.asarray(buffer.byteCount())), 12) to_visualizer = [int(sum(e) // 12 // 75) for e in chunked] self.show_visualization(to_visualizer) def show_visualization(self, to_visualizer): self.ui_manager.update_equalizer(to_visualizer) def get_audio_devices(self): return QAudioDeviceInfo.availableDevices(QAudio.AudioOutput) def get_recent_files(self): return self.recent_files_manager.get_recent_files() def clear_recent_files(self): return self.recent_files_manager.clear_recent_files() def exit(self): self.ui_manager.exit()
class Main(QWidget): def __init__(self): super().__init__() self.current_cat = "" self.categories = ["MOVIES", "SPORTS"] self.use_cases = {} self.use_cases['MOVIES'] = [ "Jokes from sitcoms", "Action sequences", "Summary", "Actor specific scenes" ] self.use_cases['SPORTS'] = [ "Goals in soccer", "Three-pointers in basketball", "Slow-mos", "Goal misses in soccer" ] self.current_use_case = "" self.chosen_actor = None # methods that should be called for # finding each use case self.processors = { "MOVIES": [ self.jokes_detector, self.action_detector, self.shot_detector, self.actor_detector ], "SPORTS": [self.goal_detector, self.three_pointer_detector, 0, 0] } self.actors = [] self.labels = [] with open('label_map.pkl', 'rb') as f: for ob in pickle.load(f): self.labels.append(int(ob[0])) self.actors.append(ob[1]) # the object of current use-case's class self.fabbit = 0 self.width, self.height = 750, 475 self.create_gui() def create_gui(self): """ Yep, creates the GUI. """ total_cats = len(self.categories) btn_height, btn_width = 70, self.width / total_cats self.btns = [0] * total_cats # add the category - movies and sports - buttons for i in range(0, total_cats): self.btns[i] = QPushButton(self.categories[i], self) self.btns[i].clicked.connect(self.update_list) self.btns[i].setGeometry(i * btn_width, 0, btn_width, btn_height) # add the side bar that containes use-cases list_width, list_height = 200, 300 self.list = QListWidget(self) self.list.clicked.connect(self.process_use_case) self.list.setGeometry(0, btn_height, list_width, list_height) # add more buttons self.file_btn = QPushButton("Choose file", self) self.file_btn.clicked.connect(self.set_file) self.file_btn.setGeometry(0, list_height + btn_height, list_width, self.height - (list_height + btn_height)) op_btn_height = (self.height - (list_height + btn_height)) / 2 op_btn_width = list_width * 3 / 4 op_btn1 = QPushButton("Find FabBits", self) op_btn1.clicked.connect(self.find_fabbits) op_btn1.setGeometry(self.width - list_width * 3 / 4, list_height + btn_height, op_btn_width, op_btn_height) op_btn2 = QPushButton("Save FabBits", self) op_btn2.clicked.connect(self.save_fabbits) op_btn2.setGeometry(self.width - list_width * 3 / 4, list_height + btn_height + op_btn_height, op_btn_width, op_btn_height) self.status_bar = QPlainTextEdit(self) self.status_bar.setReadOnly(True) self.status_bar.setGeometry(list_width, list_height + btn_height, self.width - list_width - op_btn_width, 2 * op_btn_height) self.original_stream = sys.stdout play_button_h, play_button_w = 30, 30 vw = QVideoWidget(self) vw.setGeometry( list_width, btn_height, self.width - list_width, self.height - btn_height - 2 * op_btn_height - play_button_h) self.media_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.media_player.setVideoOutput(vw) self.media_player.stateChanged.connect(self.state_change) self.media_player.positionChanged.connect(self.set_pos_player) self.media_player.durationChanged.connect(self.set_duration) self.vid_button = QPushButton(self) self.vid_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.vid_button.clicked.connect(self.play_vid) self.vid_button.setEnabled(False) self.vid_button.setGeometry( list_width, self.height - 2 * op_btn_height - play_button_h, play_button_w, play_button_h) self.vid_slider = QSlider(QtCore.Qt.Horizontal, self) self.vid_slider.sliderMoved.connect(self.set_pos_slider) self.stylesheet = """ QSlider::handle { background: qlineargradient( x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f ); border: 1px solid #5c5c5c; width : 10px; margin : -2px 0; border-radius : 3px; } QSlider::groove { background : black; } """ self.vid_slider.setStyleSheet(self.stylesheet) self.vid_slider.setGeometry( list_width + play_button_w, self.height - 2 * op_btn_height - play_button_h, self.width + list_width - play_button_w, play_button_h) self.update_list("MOVIES") self.setWindowTitle('FabBits') self.setFixedSize(self.width, self.height) self.show() def state_change(self, state): """ """ if self.media_player.state() == QMediaPlayer.PlayingState: self.vid_button.setIcon(self.style().standardIcon( QStyle.SP_MediaPause)) else: self.vid_button.setIcon(self.style().standardIcon( QStyle.SP_MediaPlay)) def play_vid(self): """ """ if self.media_player.state() == QMediaPlayer.PlayingState: self.media_player.pause() else: self.media_player.play() def set_pos_slider(self, pos): """ """ self.media_player.setPosition(pos) def set_pos_player(self, pos): """ """ self.vid_slider.setValue(pos) def set_duration(self, dur): """ """ self.vid_slider.setRange(0, dur) def update_list(self, cat): """ Sets the chosen category and updates the corresponding use-cases in the side bar. """ self.list.clear() if cat: self.current_cat = cat else: self.current_cat = self.sender().text() id = 0 for use_case in self.use_cases[self.current_cat]: obj = QListWidgetItem(use_case, self.list) obj.id = id id += 1 def process_use_case(self): """ Sets the chosen use-case and acts as an intermediary """ self.current_use_case = self.sender().currentItem().id # TODO - popup window for use cases that need extra info # like actor specific scenes to ask for actor name if self.current_cat == "MOVIES" and self.current_use_case == 3: item, ok = QInputDialog.getItem(self, 'Choose ..', 'Select an actor', self.actors, 0, False) if ok and item: self.chosen_actor = item def find_fabbits(self): """ Finds the use-case. """ cat = self.current_cat use_case = self.current_use_case f = lambda: self.processors[cat][use_case]() thread = HelperThread("Finding FabBit 1", f) thread.start() def jokes_detector(self): print("processing") jokes = LaughDetector(self.file) jokes.process() self.fabbit = jokes print("done processing fabbits for " + self.file) timestamps = self.fabbit.get_timestamps() self.highlight(timestamps) def shot_detector(self): print("processing") summary = DetectShots(self.file) summary.process() self.fabbit = summary print("Done processing fabbits for " + self.file + ". Click Save FabBits to, well, save.") def action_detector(self): print("processing") action = DetectAction(self.file) action.process() self.fabbit = action timestamps = self.fabbit.get_timestamps() self.highlight(timestamps) def actor_detector(self): if not self.chosen_actor: print("You haven't selected an actor.") return actor_label = 0 for i in range(0, len(self.actors)): if self.actors[i] == self.chosen_actor: actor_label = self.labels[i] actor_specific = DetectActor(self.file, actor_label) actor_specific.process() self.fabbit = actor_specific timestamps = self.fabbit.get_timestamps() self.highlight(timestamps) def goal_detector(self): print("processing") goals = DetectGoal(self.file) goals.process() self.fabbit = goals print("done processing fabbits for " + self.file) timestamps = self.fabbit.get_timestamps() self.highlight(timestamps) def three_pointer_detector(self): print("processing") tpointers = Detect3Pointers(self.file) tpointers.process() self.fabbits = tpointers print("done processing fabbits for " + self.file) timestamps = self.fabbit.get_timestamps() self.highlight(timestamps) def highlight(self, timestamps): duration = timestamps["duration"] timestamps = timestamps["timestamps"] style = """ QSlider::handle { background: qlineargradient( x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f ); border: 1px solid #5c5c5c; width : 10px; margin : -2px 0; border-radius : 3px; } """ style += """QSlider::groove { background : qlineargradient(x1:0, y1:0, x2:1, y2:0, stop : 0 black""" for t in timestamps: style += ",stop:" + str(t['s'] / duration - 0.00001) + " black" style += ",stop:" + str(t['s'] / duration) + " blue" style += ",stop:" + str(t['e'] / duration) + " blue" style += ",stop:" + str(t['e'] / duration + 0.00001) + " black" print(t['s'], t['e'], t['s'] / duration, t['e'] / duration) style += ");}" self.vid_slider.setStyleSheet(style) def save_fabbits(self): sys.stdout = self.original_stream thread = HelperThread("Saving", self.fabbit.save) thread.start() def set_file(self): """ For file dialog to get input video """ self.file = QFileDialog.getOpenFileName(self, 'Open file', '/home') if self.file[0]: self.file = self.file[0] self.media_player.setMedia( QMediaContent(QtCore.QUrl.fromLocalFile(self.file))) self.vid_button.setEnabled(True) sys.stdout = StatusStream(self.status_bar) self.vid_slider.setStyleSheet(self.stylesheet) self.filename = self.file[self.file.rfind('/') + 1:] print("loaded " + self.filename)
def __init__(self): super(MainWindow, self).__init__() self.setAttribute(Qt.WA_QuitOnClose, False) self.tIcon = QIcon( os.path.join(os.path.dirname(sys.argv[0]), "radio_bg.png")) self.setWindowIcon(self.tIcon) self.setGeometry(0, 0, 700, 400) self.setContentsMargins(6, 6, 6, 6) self.setStyleSheet(myStyleSheet(self)) self.setWindowTitle("Radio Suche") self.genreList = genres.splitlines() self.findfield = QLineEdit() self.findfield.setFixedWidth(250) self.findfield.addAction(QIcon.fromTheme("edit-find"), 0) self.findfield.setPlaceholderText("Suchbegriff eingeben und RETURN ") self.findfield.returnPressed.connect(self.findStations) self.findfield.setClearButtonEnabled(True) self.field = QPlainTextEdit() self.field.setContextMenuPolicy(Qt.CustomContextMenu) self.field.customContextMenuRequested.connect( self.contextMenuRequested) self.field.cursorPositionChanged.connect(self.selectLine) self.field.setWordWrapMode(QTextOption.NoWrap) ### genre box self.combo = QComboBox() self.combo.currentIndexChanged.connect(self.comboSearch) self.combo.addItem("wähle Genre") for m in self.genreList: self.combo.addItem(m) self.combo.setFixedWidth(150) ### toolbar ### self.tb = self.addToolBar("tools") self.tb.setContextMenuPolicy(Qt.PreventContextMenu) self.tb.setMovable(False) self.setCentralWidget(self.field) self.tb.addWidget(self.findfield) self.tb.addSeparator() self.tb.addWidget(self.combo) ### player ### self.player = QMediaPlayer() self.player.metaDataChanged.connect(self.metaDataChanged) self.startButton = QPushButton("Wiedergabe") self.startButton.setIcon(QIcon.fromTheme("media-playback-start")) self.startButton.clicked.connect(self.getURLtoPlay) self.stopButton = QPushButton("Stop") self.stopButton.setIcon(QIcon.fromTheme("media-playback-stop")) self.stopButton.clicked.connect(self.stopPlayer) self.statusBar().addPermanentWidget(self.startButton) self.statusBar().addPermanentWidget(self.stopButton) ## actions self.addToRadiolistAction = QAction( QIcon.fromTheme("add"), "zu myRadio Senderliste hinzufügen", self, triggered=self.addToRadiolist) self.getNameAction = QAction(QIcon.fromTheme("edit-copy"), "Sendername kopieren", self, triggered=self.getName) self.getUrlAction = QAction(QIcon.fromTheme("edit-copy"), "Sender-URL kopieren", self, triggered=self.getURL) self.getNameAndUrlAction = QAction(QIcon.fromTheme("edit-copy"), "Name,URL kopieren", self, triggered=self.getNameAndUrl) self.getURLtoPlayAction = QAction( QIcon.fromTheme("media-playback-start"), "Sender spielen", self, shortcut="F6", triggered=self.getURLtoPlay) self.addAction(self.getURLtoPlayAction) self.stopPlayerAction = QAction(QIcon.fromTheme("media-playback-stop"), "Wiedergabe stoppen", self, shortcut="F7", triggered=self.stopPlayer) self.addAction(self.stopPlayerAction) self.helpAction = QAction(QIcon.fromTheme("help-info"), "Hilfe", self, shortcut="F1", triggered=self.showHelp) self.addAction(self.helpAction) self.statusBar().showMessage("Welcome", 0) self.modified = False
self.label2.setText("你还有{}次暂停时光机的机会哦".format(self.total_times - self.hit_times)) if __name__ == "__main__": app = QApplication([]) app.setStyle('Fusion') # music load and player initialization playlist = QMediaPlaylist() filenames = ['background.mp3'] for filename in filenames: fullpath = QDir.current().absoluteFilePath(filename) url = QUrl.fromLocalFile(fullpath) playlist.addMedia(QMediaContent(url)) playlist.setPlaybackMode(QMediaPlaylist.Loop) player = QMediaPlayer() player.setPlaylist(playlist) # player.play() # events load and initilization event_list = [] with open('./major_events.txt',encoding='utf-8') as event_file: lines=event_file.readlines() for line in lines: line=line.strip() event=line.split('#') event_list.append(Event(event[0],event[1])) event_list.sort(key=lambda x: x.event_time) main_window = MainWindow(event_list)
def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(975, 558) Dialog.setStyleSheet("background-color: rgb(0, 85, 255);\n" "background-color: rgb(255, 170, 0);") self.checkBox = QtWidgets.QCheckBox(Dialog) self.checkBox.setGeometry(QtCore.QRect(10, 300, 81, 21)) self.checkBox.setMinimumSize(QtCore.QSize(81, 0)) self.checkBox.setMaximumSize(QtCore.QSize(81, 21)) font = QtGui.QFont() font.setPointSize(8) self.checkBox.setFont(font) self.checkBox.setObjectName("checkBox") self.checkBox_2 = QtWidgets.QCheckBox(Dialog) self.checkBox_2.setGeometry(QtCore.QRect(10, 340, 81, 20)) self.checkBox_2.setObjectName("checkBox_2") self.checkBox_3 = QtWidgets.QCheckBox(Dialog) self.checkBox_3.setGeometry(QtCore.QRect(10, 380, 81, 20)) self.checkBox_3.setObjectName("checkBox_3") self.checkBox_4 = QtWidgets.QCheckBox(Dialog) self.checkBox_4.setGeometry(QtCore.QRect(10, 420, 81, 20)) self.checkBox_4.setObjectName("checkBox_4") self.checkBox_5 = QtWidgets.QCheckBox(Dialog) self.checkBox_5.setGeometry(QtCore.QRect(10, 460, 81, 20)) self.checkBox_5.setObjectName("checkBox_5") self.checkBox_6 = QtWidgets.QCheckBox(Dialog) self.checkBox_6.setGeometry(QtCore.QRect(10, 500, 81, 20)) self.checkBox_6.setObjectName("checkBox_6") self.line_2 = QtWidgets.QFrame(Dialog) self.line_2.setGeometry(QtCore.QRect(0, 59, 981, 21)) font = QtGui.QFont() font.setPointSize(7) font.setBold(False) font.setWeight(50) self.line_2.setFont(font) self.line_2.setFrameShape(QtWidgets.QFrame.HLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName("line_2") self.pushButton = QtWidgets.QPushButton(Dialog) self.pushButton.setGeometry(QtCore.QRect(120, 297, 93, 31)) self.pushButton.setStyleSheet("background-color: rgb(255, 255, 255);") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(Dialog) self.pushButton_2.setGeometry(QtCore.QRect(120, 340, 93, 28)) self.pushButton_2.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(Dialog) self.pushButton_3.setGeometry(QtCore.QRect(120, 380, 93, 28)) self.pushButton_3.setStyleSheet( "background-color: rgb(255, 255, 255);\n" "\n" "") self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(Dialog) self.pushButton_4.setGeometry(QtCore.QRect(120, 420, 93, 28)) self.pushButton_4.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_4.setObjectName("pushButton_4") self.pushButton_5 = QtWidgets.QPushButton(Dialog) self.pushButton_5.setGeometry(QtCore.QRect(120, 460, 93, 28)) self.pushButton_5.setStyleSheet( "background-color: rgb(255, 255, 255);\n" "") self.pushButton_5.setObjectName("pushButton_5") self.pushButton_6 = QtWidgets.QPushButton(Dialog) self.pushButton_6.setGeometry(QtCore.QRect(120, 500, 93, 28)) self.pushButton_6.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_6.setObjectName("pushButton_6") self.line = QtWidgets.QFrame(Dialog) self.line.setGeometry(QtCore.QRect(213, 70, 20, 501)) font = QtGui.QFont() font.setPointSize(7) font.setBold(False) font.setWeight(50) self.line.setFont(font) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.pushButton_7 = QtWidgets.QPushButton(Dialog) self.pushButton_7.setGeometry(QtCore.QRect(10, 100, 201, 28)) self.pushButton_7.setStyleSheet( "background-color: qradialgradient(spread:repeat, cx:0.5, cy:0.5, radius:0.077, fx:0.5, fy:0.5, stop:0 rgba(0, 169, 255, 147), stop:0.497326 rgba(0, 0, 0, 147), stop:1 rgba(0, 169, 255, 147));\n" "background-color: rgb(255, 255, 255);") self.pushButton_7.setObjectName("pushButton_7") self.pushButton_7.clicked.connect(self.open_file) self.pushButton_8 = QtWidgets.QPushButton(Dialog) self.pushButton_8.setGeometry(QtCore.QRect(10, 160, 201, 28)) self.pushButton_8.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_8.setObjectName("pushButton_8") self.line_3 = QtWidgets.QFrame(Dialog) self.line_3.setGeometry(QtCore.QRect(230, 510, 741, 16)) self.line_3.setFrameShape(QtWidgets.QFrame.HLine) self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_3.setObjectName("line_3") self.pushButton_9 = QtWidgets.QPushButton(Dialog) self.pushButton_9.setGeometry(QtCore.QRect(450, 520, 131, 28)) self.pushButton_9.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_9.setObjectName("pushButton_9") self.pushButton_9.clicked.connect(self.play_video) self.pushButton_10 = QtWidgets.QPushButton(Dialog) self.pushButton_10.setGeometry(QtCore.QRect(730, 520, 93, 28)) self.pushButton_10.setStyleSheet( "background-color: rgb(255, 255, 255);\n" "border-color: rgb(0, 0, 0);") self.pushButton_10.setObjectName("pushButton_10") self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(470, 20, 141, 31)) font = QtGui.QFont() font.setFamily("MS Sans Serif") font.setPointSize(17) font.setBold(True) font.setItalic(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName("label") self.frame = QtWidgets.QFrame(Dialog) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.frame.setGeometry(QtCore.QRect(260, 90, 151, 101)) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName("frame") self.video1 = QVideoWidget(self.frame) self.video1.setGeometry(QtCore.QRect(0, 0, 121, 101)) self.video1.setStyleSheet("background-color: rgb(0, 0, 0);") self.video1.setObjectName("video1") self.pushButton_7.raise_() self.checkBox.raise_() self.checkBox_2.raise_() self.checkBox_3.raise_() self.checkBox_4.raise_() self.checkBox_5.raise_() self.checkBox_6.raise_() self.line_2.raise_() self.pushButton.raise_() self.pushButton_2.raise_() self.pushButton_3.raise_() self.pushButton_4.raise_() self.pushButton_5.raise_() self.pushButton_6.raise_() self.line.raise_() self.pushButton_8.raise_() self.line_3.raise_() self.pushButton_9.raise_() self.pushButton_10.raise_() self.label.raise_() self.frame.raise_() self.mediaPlayer.setVideoOutput(self.video1) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog)
def __init__(self): super(VideoPlayer, self).__init__() self._player = QMediaPlayer() self._playlist = QMediaPlaylist() self._stopped = True
class Prompter(QThread): signal_label_text = pyqtSignal('QString') signal_start_duration = pyqtSignal(int, int) signal_toggle_lights = pyqtSignal(bool) signal_initiate_movie = pyqtSignal('QString') signal_sounds_clicked = pyqtSignal(int) signal_eyes_open = pyqtSignal(bool) def __init__(self): QThread.__init__(self) self.current_challenge = None self.challenges = defaultdict(list) self.progress = ProgressBarThread.ProgressBarThread() self.progress.signal_progress.connect(self.change_progress) self.progress.signal_toggle_lights.connect(self.prompter_toggle_lights) self.progress.signal_start_new_stage.connect(self.start_new_stage) #self.camera_thread = Camera.WebcamRecorder() # Main Camera thread self.eeg_thread = EEG.EEG() # Main EEG client thread self.eeg_thread.sample_signal.connect(self.get_samples) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.StreamPlayback) self.beeper_thread = Beeper.Beeper() # beeper thread self.current_samples = [] self.current_original_duration = 0 self.current_eyes_open = True self.current_movie = "" self.used_challenges = [] self.current_state_filename = "" self.session_labels_dict = dict() self.symbols_count = 15 # number of repetitions for each class self.symbols_status = defaultdict(lambda: 0) # keep track # EEG samples collection self.current_log_saving = False self.current_log_filename = "" def __del__(self): self.wait() # loads challenges to a dict of lists def load_data(self): with open("data.json") as f: data = json.load(f) for key, challenges in data.items(): for challenge in challenges: cal = Challenge.Challenge(key, challenge["name"], challenge["stages_duration"], challenge["stages_data"], challenge["text"], challenge["eyes"], challenge["index"]) self.challenges[key].append(cal) self.eeg_thread.start() def pick_challenge(self, level=1): # pick a challenge and guard against same sequential picks in a row tryhard = False if tryhard: no_repeat = 5 rand_key = random.choice(list(self.challenges)) lst = self.challenges[rand_key] try: self.current_challenge = lst[random.randint(0, len(self.challenges[rand_key]) - 1)] except Exception as e: print("QUITTING. ALL CHALLENGES DONE") self.quit() print(self.current_challenge) lower_limit = 0 if len(self.used_challenges) < no_repeat else len(self.used_challenges) - no_repeat if level > 25: # in case of too many recursions, reset all level = 1 self.used_challenges = [] if self.current_challenge in self.used_challenges[lower_limit:] or \ self.check_symbol_status_done(self.current_challenge.get_index()): # or the challenge is done print("Collision found: " + str(self.used_challenges) + " contains " + str(self.current_challenge)) done = True for j in range(1, len(self.challenges) + 1): if not self.check_symbol_status_done(j): done = False break if done: print("ALL CHALLENGES DONE, QUITTING") sys.exit(0) self.pick_challenge(level=level + 1) # pick a new one self.used_challenges.append(self.current_challenge) self.symbols_status[self.current_challenge.get_index()] += 1 # increment status info else: rand_key = random.choice(["left_hand", "right_hand"]) lst = self.challenges[rand_key] self.current_challenge = lst[0] # check if we've already done all of the tries for a symbol def check_symbol_status_done(self, index): return self.symbols_status[index] >= self.symbols_count def get_samples(self, index, voltages, accelerometer): if self.current_log_saving: # if the saving is turned on (we are in Stage 3) self.current_samples.append((index, voltages, accelerometer)) def record_camera(self): self.current_log_saving = True self.camera_thread.set_details(120, "out/" + self.current_log_filename + "_" + str(int(time.time()))) self.camera_thread.start() def save_log(self): with open(self.current_log_filename + "_dataset.csv", "a", newline='') as f: dataset_writer = csv.writer(f, delimiter=",") for item in self.current_samples: if (len(item[1]) == 8): dataset_writer.writerow([item[0], item[1][0], item[1][1], item[1][2], item[1][3], item[1][4], item[1][5], item[1][6], item[1][7], item[2][0], item[2][1], item[2][2], self.current_challenge.get_index()]) else: print("INCOMPLETE SAMPLE DETECTED.") self.current_samples = [] # and initiate the list again def get_another_challenge(self, stage=1, anew=False): print("CURRENT STAGE: " + str(stage)) if anew: self.pick_challenge() if stage > 3: stage = 1 self.save_log() # save new samples after every level #self.camera_thread.end = True # split the camera feed to a new file #self.record_camera() # and begin recording to another file self.get_another_challenge(stage, True) # we begin anew, overflow # self.current_log_saving = False # turn off log saving, we later turn it on in the Stage 3 # stage 2 is when the actual task is being carried out if stage == 1: # text stage self.current_original_duration = self.current_challenge.get_duration(stage) elif stage == 2: # stage for focusing or doing self.current_original_duration = random.uniform(10, 15) else: # pause stage self.current_original_duration = random.uniform(5, 7) self.prompter_toggle_lights(True) # default: color red is on - do nothing, yet self.signal_start_duration.emit(int(self.current_original_duration), int(self.current_original_duration)) print("Current original duration set to " + str(self.current_original_duration)) self.current_eyes_open = self.current_challenge.get_eyes() self.current_movie = self.current_challenge.get_data(stage) self.progress.set_stage(stage) self.progress.set_remaining(self.current_original_duration) if stage == 1: self.signal_label_text.emit(self.current_challenge.text) self.save_current_state_change(self.current_challenge.get_index(), stage, 0, 0, 1, # text changed 0, 0) # self.camera_thread.quit() # turn of the camera if it is not already self.beeper_thread.set_stage_sound(self.current_challenge.get_data(2)) self.beeper_thread.start() self.save_current_state_change(self.current_challenge.get_index(), stage, 0, 0, 0, 1, # challenge sound emitted 0) self.signal_eyes_open.emit(self.current_eyes_open) self.save_current_state_change(self.current_challenge.get_index(), stage, 0, 1, # eyes changed 0, 0, 0) elif stage == 2: # Stage 2 self.current_log_saving = True # we begin recording if self.current_challenge.get_index() == 1: # left hand self.current_movie = "challenges/left_arrow.png" elif self.current_challenge.get_index() == 2: # right hand self.current_movie = "challenges/right_arrow.png" else: self.current_movie = "challenges/medi.png" self.initiate_movie() self.save_current_state_change(self.current_challenge.get_index(), stage, 0, 0, 0, 0, 1) # image changed self.beeper_thread.set_start_sound() self.beeper_thread.start() self.save_current_state_change(self.current_challenge.get_index(), stage, 0, 0, 0, 2, # start sound emitted 0) self.prompter_toggle_lights(False) self.save_current_state_change(self.current_challenge.get_index(), stage, 1, # colors changed 0, 0, 0, 0) else: # stage 3 # pause between stages print(self.symbols_status) self.current_log_saving = False # turn off recording self.initiate_movie() self.save_current_state_change(self.current_challenge.get_index(), stage, 0, 0, 0, 0, 1) # image changed self.beeper_thread.set_end_sound() # end of stage self.beeper_thread.start() self.save_current_state_change(self.current_challenge.get_index(), stage, 0, 0, 0, 3, # end sound emitted 0) self.prompter_toggle_lights(True) self.save_current_state_change(self.current_challenge.get_index(), stage, 1, # colors changed 0, 0, 0, 0) self.progress.start() def change_sounds(self, k): self.mediaPlayer.setVolume(k * 50) def initiate_movie(self): self.signal_initiate_movie.emit(self.current_movie) def prompter_toggle_lights(self, red_first): self.signal_toggle_lights.emit(red_first) def start_new_stage(self, stage): self.get_another_challenge(stage) def change_progress(self, duration): self.signal_start_duration.emit(duration, self.current_original_duration) def save_current_state_change(self, index=0, stage=0, color_lights=0, eyes=0, text=0, sound=0, image=0): self.session_labels_dict[str(int(time.time()))] = [ index, stage, color_lights, eyes, text, sound, image ] with open("out/" + self.current_log_filename + "_labels.json", "a") as f: json.dump(self.session_labels_dict, f) self.session_labels_dict def run(self): print("Starting Challenges") self.load_data() self.current_log_filename = str(int(time.time())) self.current_state_filename = self.current_log_filename + "_labels" fieldnames = ['timestamp', 'node1', 'node2', 'node3', 'node4', 'node5', 'node6', 'node7', 'node8', 'accX', 'accY', 'accZ', 'class'] with open(self.current_log_filename + "_dataset.csv", "w", newline='') as f: dataset_writer = csv.writer(f, delimiter=",") dataset_writer.writerow(fieldnames) self.get_another_challenge(1, True)
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( "rtsp://127.0.0.1:5554/user=user&password=&channel=1&stream=1.sdp?real_stream" ) 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( "rtsp://127.0.0.1:5554/user=user&password=&channel=1&stream=1.sdp?real_stream" )) 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()
def init_ui(self): conf_for_blank = ''' QPushButton{ border: none; margin: 0px; padding: 0px; background-color:#F0F0F0; } ''' config = ''' QPushButton{ border: none; margin: 0px; padding: 0px; background-color:#F0F0F0; } QPushButton:hover{ background-color: #B4B4B4; border-radius:7px; width: 30px; } ''' global hboxLayout global hboxLayout2 global vboxLayout global videowidget global openBtn # создание экземпляра(объекта) класса QMediaPlayer() и передача аргуметов # QMediaPlayer.VideoSurface указывает что он 'служит' для воспроизведения видео self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) # создание экземпляра(объекта) класса QVideoWidget() videowidget = QVideoWidget() videowidget.setStyleSheet('background-color: #B4B4B4;') # создание button(кнопки открыть) openBtn = QPushButton() openBtn.setStyleSheet(config) openBtn.setIcon(QIcon(resource_path(r'ico\folders.png'))) openBtn.setIconSize(QSize(20, 20)) openBtn.clicked.connect(self.open_file) openBtn.setToolTip('Открытие папок для просмотра файлов') openBtn.setToolTipDuration(2500) # создание button (кнопки для запуска) self.playBtn = QPushButton() self.playBtn.setEnabled(False) self.playBtn.setFlat(True) self.playBtn.setStyleSheet(config) self.playBtn.setIcon(QIcon(resource_path(r'ico\play.png'))) self.playBtn.setIconSize(QSize(40, 40)) self.playBtn.clicked.connect(self.play_video) # self.playBtn.clicked.connect(self.play_video) # создание button(кнопки для перемотки вперед) self.forwardBtn = QPushButton() self.forwardBtn.setEnabled(False) self.forwardBtn.setIcon(QIcon(resource_path(r'ico\forward.png'))) self.forwardBtn.setStyleSheet(config) self.forwardBtn.setIconSize(QSize(20, 20)) self.forwardBtn.clicked.connect(self.go_forward) # создание button (для перемотки назад) self.backBtn = QPushButton() self.backBtn.setEnabled(False) self.backBtn.setIcon(QIcon(resource_path(r'ico\backward .png'))) self.backBtn.setStyleSheet(config) self.backBtn.setIconSize(QSize(20, 20)) self.backBtn.clicked.connect(self.go_back) # для volume(громкости) self.volumeBtn = QPushButton() self.volumeBtn.setObjectName('volume_btn') self.volumeBtn.setIcon(QIcon(resource_path(r'ico\volume1.png'))) self.volumeBtn.setStyleSheet(config) self.volumeBtn.setIconSize(QSize(17, 17)) self.volumeBtn.clicked.connect(self.volume) # настройка button(кнопок) self.screenBtn = QPushButton() self.screenBtn.setObjectName('fullscreen') self.screenBtn.setStyleSheet(config) self.screenBtn.setIcon(QIcon(resource_path(r'ico\fullscreen.png'))) self.screenBtn.setIconSize(QSize(19, 19)) self.screenBtn.clicked.connect(self.full_screen) self.screenBtn.setToolTip('Переключить на полноэкранный размер') self.screenBtn.setToolTipDuration(2500) # ----- кнопки для пустых мест ----- # # создание button (для окна настроек) self.imageBtn = QPushButton() self.imageBtn.setIcon(QIcon(resource_path(r'ico\photo.png'))) self.imageBtn.setToolTip( 'Открывает второе окно которое позволяет взимодействовать с изображениями' ) self.imageBtn.setIconSize((QSize(18, 18))) self.imageBtn.setEnabled(True) self.imageBtn.setStyleSheet(config) self.themeBtn = Switch(thumb_radius=11, track_radius=8) self.themeBtn.setObjectName('default') self.themeBtn.setToolTip('Изменить задний фон') self.themeBtn.clicked.connect(self.change_to_dark_theme) self.blankBtn = QPushButton() self.blankBtn.setEnabled(False) self.blankBtn.setStyleSheet(conf_for_blank) # --------------------------------------- # # создание slider'а self.slider = MySlider(orient=Qt.Horizontal) self.slider.sliderMoved.connect(self.set_position) # создания slider для volume self.hslider = MySlider(orient=Qt.Horizontal) self.hslider.setRange(0, 100) self.hslider.setMaximumHeight(7) self.hslider.sliderMoved.connect(self.set_volume_position) self.hslider.setMaximumWidth(80) self.hslider.setSliderPosition(100) # создания label'а self.label1 = QLabel('0:00 /') self.label1.setToolTip('Прошло времени') self.label1.setFont(QFont('SansSerif', 8, QFont.Bold)) self.label2 = QLabel('0:00') self.label2.setToolTip('Общая продолжительность') self.label2.setFont(QFont('SansSerif', 8, QFont.Bold)) # создание hbox layout hboxLayout = QHBoxLayout() hboxLayout.setContentsMargins(0, 0, 0, 0) # создание hbox2 layout hboxLayout2 = QHBoxLayout() hboxLayout.setContentsMargins(0, 0, 0, 0) # добавления виджетов в hbox2 layout hboxLayout2.addWidget(self.label1) hboxLayout2.addWidget(self.label2) hboxLayout2.addWidget(self.slider) hboxLayout2.addWidget(self.volumeBtn) hboxLayout2.addWidget(self.hslider) # добавления виджетов в hbox layout hboxLayout.addWidget(self.themeBtn) hboxLayout.addWidget(self.blankBtn) hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.backBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.forwardBtn) hboxLayout.addWidget(self.imageBtn) hboxLayout.addWidget(self.screenBtn) # self.frame = MyFrame() vboxLayout = QVBoxLayout() # vboxLayout.addWidget(MyFrame()) vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout2) vboxLayout.addLayout(hboxLayout) self.setLayout(vboxLayout) self.mediaPlayer.setVideoOutput(videowidget) # обработчики медиа сигналов self.mediaPlayer.stateChanged.connect(self.media_state_changed) self.mediaPlayer.positionChanged.connect(self.position_changed) self.mediaPlayer.durationChanged.connect(self.duration_changed) self.mediaPlayer.volumeChanged.connect(self.set_volume_position) self.mediaPlayer.durationChanged.connect(self.duration_volume) # Несколько функций которые вызываются во время взаимодействия с клавишами для удобства self.volumeMinSc = QShortcut(QKeySequence('Down'), self) self.volumeMinSc.activated.connect(self.min_volume) self.volumePlusSc = QShortcut(QKeySequence('Up'), self) self.volumePlusSc.activated.connect(self.plus_volume) self.forwardSc = QShortcut(QKeySequence('Right'), self) self.forwardSc.activated.connect(self.go_forward_with_key) self.backSc = QShortcut(QKeySequence('Left'), self) self.backSc.activated.connect(self.go_back_with_key) self.fullscreenSc = QShortcut(QKeySequence('F'), self) self.fullscreenSc.activated.connect(self.full_screen)
class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Video Player Iyonissio") self.setGeometry(350, 100, 700, 500) self.setWindowIcon(QIcon('player.png')) p = self.palette() p.setColor(QPalette.Window, Qt.black) self.setPalette(p) self.init_ui() self.show() def init_ui(self): #Criando o Objecto Media player self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) #Criando o videoWidget (Tela do Video) videowidget = QVideoWidget() #Criando Butoes de Abertura openBtn = QPushButton('Abra o Video') openBtn.clicked.connect(self.open_file) #Criando Butoes para rodar o video(play) self.playBtn = QPushButton() self.playBtn.setEnabled(False) self.playBtn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playBtn.clicked.connect(self.play_video) #Criando Slider self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, 0) self.slider.sliderMoved.connect(self.set_position) #crate Label self.label = QLabel() self.label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) #criando Caixa layout hboxLayout = QHBoxLayout() hboxLayout.setContentsMargins(0, 0, 0, 0) #set widgets hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.slider) #criando vbox layout vboxLayout = QVBoxLayout() vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout) vboxLayout.addWidget(self.label) self.setLayout(vboxLayout) self.mediaPlayer.setVideoOutput(videowidget) #Pause Botao self.mediaPlayer.stateChanged.connect(self.mediastate_changed) self.mediaPlayer.positionChanged.connect(self.position_changed) self.mediaPlayer.durationChanged.connect(self.duration_changed) def open_file(self): filename, _ = QFileDialog.getOpenFileName(self, "Abrir Video") if filename != '': self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(filename))) self.playBtn.setEnabled(True) def play_video(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() def mediastate_changed(self, state): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playBtn.setIcon(self.style().standardIcon( QStyle.SP_MediaPause)) else: self.playBtn.setIcon(self.style().standardIcon( QStyle.SP_MediaPlay)) def position_changed(self, position): self.slider.setValue(position) def duration_changed(self, duration): self.slider.setRange(0, duration) def set_position(self, position): self.mediaPlayer.setPosition(position) def handle_errors(self): self.playBtn.setEnabled(False) self.label.setText("Error: " + self.mediaPlayer.errorString())
def __init__(self, statusBar): super().__init__() # store active image ID self.active_image_id = str() # Saves multiple duplicate windows references: self.duplicateRefs = {} # Gets status bar from QMainWindow: self.statusBar = statusBar # Initializes all window elements: self.folderField = QLineEdit() self.folderButton = QPushButton() self.folderTreeCheckbox = QCheckBox("Include sub-folders") self.processButton = QPushButton("Process media files") self.duplicateButton = QPushButton("Find duplicates") self.reindexButton = QPushButton("Reindex database files") self.tableTabs = QTabWidget() # init main images list table self.imageListTable = QTableWidget() # set main images list table fields unchanged self.imageListTable.setEditTriggers(QTableWidget.NoEditTriggers) # init main videos list table self.videoListTable = QTableWidget() # set main videos list table fields unchanged self.videoListTable.setEditTriggers(QTableWidget.NoEditTriggers) # set up image fields and elements self.imageField = QLabel() self.imageNameField = QLabel() self.imageParamsField = QLabel() self.imageCopyButton = QPushButton("Copy image") self.imageCopyButton.setIcon(QIcon("gui/static/icon_copy.png")) self.imageCopyButton.clicked.connect(self.copy_image_path) self.imageViewButton = QPushButton("View image") self.imageViewButton.setIcon(QIcon("gui/static/icon_open_image.svg")) self.imageViewButton.clicked.connect(self.open_image_file) self.imageOpenDirButton = QPushButton("Open dir") self.imageOpenDirButton.setIcon( QIcon("gui/static/icon_open_folder.svg")) self.imageOpenDirButton.clicked.connect(self.open_image_path) self.imageDeleteButton = QPushButton("Delete") self.imageDeleteButton.setIcon( QIcon("gui/static/icon_delete_file.png")) self.imageDeleteButton.clicked.connect(self.delete_image) self.videoField = QVideoWidget() self.videoPlayer = QMediaPlayer() # Adjusts settings for the window elements: self.folderField.setDisabled(True) self.folderButton.setIcon(QIcon("gui/static/icon_process_folder.png")) self.folderButton.clicked.connect(self.set_folder) self.processButton.clicked.connect(self.process_files) self.processButton.setFixedWidth(160) self.processButton.setDisabled(True) self.duplicateButton.clicked.connect(self.find_duplicates) self.duplicateButton.setFixedWidth(160) self.reindexButton.clicked.connect(self.reindex_db_data) self.reindexButton.setFixedWidth(160) # prepare tables for images and videos self.imagesTab = self.tableTabs.insertTab(0, self.imageListTable, "Images") self.videosTab = self.tableTabs.insertTab(1, self.videoListTable, "Videos") # images list table setup self.imageListTable.setColumnCount(len(self.COLUMNS_DICT.keys())) self.imageListTable.setHorizontalHeaderLabels(self.COLUMNS_DICT.keys()) self.imageListTable.verticalHeader().setVisible(False) self.imageListTable.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.imageListTable.setSortingEnabled(True) self.imageListTable.cellClicked.connect(self.show_image) # videos list table setup self.videoListTable.setColumnCount(len(self.COLUMNS_DICT.keys())) self.videoListTable.setHorizontalHeaderLabels(self.COLUMNS_DICT.keys()) self.videoListTable.verticalHeader().setVisible(False) self.videoListTable.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.videoListTable.setSortingEnabled(True) self.videoListTable.cellClicked.connect(self.show_video) # set images and videos duplicates columns width self.set_columns_width() # Places the window elements on the window: # Top-left cell of main grid box: subGridBox = QWidget() subGrid = QGridLayout() subGrid.addWidget(self.folderField, 0, 0) subGrid.addWidget(self.folderButton, 0, 1) subGrid.addWidget(self.folderTreeCheckbox, 1, 0) subGrid.addWidget(self.processButton, 2, 0, 1, 2, Qt.AlignCenter) subGrid.addWidget(self.duplicateButton, 3, 0, 1, 2, Qt.AlignCenter) subGrid.addWidget(self.reindexButton, 4, 0, 1, 2, Qt.AlignCenter) subGridBox.setLayout(subGrid) # image data grid box imageGridBox = QWidget() imageGrid = QGridLayout() imageGrid.addWidget(self.imageField, 0, 0, 1, 4, Qt.AlignCenter) # add image buttons imageGrid.addWidget(self.imageCopyButton, 1, 0, 1, 1) imageGrid.addWidget(self.imageViewButton, 1, 1, 1, 1) imageGrid.addWidget(self.imageOpenDirButton, 1, 2, 1, 1) imageGrid.addWidget(self.imageDeleteButton, 1, 3, 1, 1) imageGrid.addWidget(self.imageNameField, 2, 0, 1, 1) imageGrid.addWidget(self.imageParamsField, 2, 3, 1, 1) imageGridBox.setLayout(imageGrid) # Main grid box: self.mainGrid = QGridLayout() self.mainGrid.addWidget(subGridBox, 0, 0) self.mainGrid.addWidget(self.tableTabs, 1, 0) self.mainGrid.addWidget(imageGridBox, 1, 1) self.mainGrid.addWidget(self.videoField, 0, 1, 2, 1) self.mainGrid.setColumnMinimumWidth(0, 400) self.mainGrid.setRowMinimumHeight(1, 600) self.mainGrid.setColumnStretch(1, 1) self.setLayout(self.mainGrid) # Creates a QThread instance: self.thread = ProcessingThread(self.folderField, self.imageListTable, self.videoListTable, self.folderTreeCheckbox) self.thread.finishedTrigger.connect(self.finish_thread) # filling table while first run self.reindex_db_data() # hide image interface self.hide_active_image()
class Window(QWidget): COLUMNS_DICT = { # "Column label": {'index': column_ID, 'width': column_width} "ID": { "index": 0, "width": 25 }, "File name": { "index": 1, "width": 165 }, "Format": { "index": 2, "width": 50 }, "Dup": { "index": 3, "width": 5 }, } def __init__(self, statusBar): super().__init__() # store active image ID self.active_image_id = str() # Saves multiple duplicate windows references: self.duplicateRefs = {} # Gets status bar from QMainWindow: self.statusBar = statusBar # Initializes all window elements: self.folderField = QLineEdit() self.folderButton = QPushButton() self.folderTreeCheckbox = QCheckBox("Include sub-folders") self.processButton = QPushButton("Process media files") self.duplicateButton = QPushButton("Find duplicates") self.reindexButton = QPushButton("Reindex database files") self.tableTabs = QTabWidget() # init main images list table self.imageListTable = QTableWidget() # set main images list table fields unchanged self.imageListTable.setEditTriggers(QTableWidget.NoEditTriggers) # init main videos list table self.videoListTable = QTableWidget() # set main videos list table fields unchanged self.videoListTable.setEditTriggers(QTableWidget.NoEditTriggers) # set up image fields and elements self.imageField = QLabel() self.imageNameField = QLabel() self.imageParamsField = QLabel() self.imageCopyButton = QPushButton("Copy image") self.imageCopyButton.setIcon(QIcon("gui/static/icon_copy.png")) self.imageCopyButton.clicked.connect(self.copy_image_path) self.imageViewButton = QPushButton("View image") self.imageViewButton.setIcon(QIcon("gui/static/icon_open_image.svg")) self.imageViewButton.clicked.connect(self.open_image_file) self.imageOpenDirButton = QPushButton("Open dir") self.imageOpenDirButton.setIcon( QIcon("gui/static/icon_open_folder.svg")) self.imageOpenDirButton.clicked.connect(self.open_image_path) self.imageDeleteButton = QPushButton("Delete") self.imageDeleteButton.setIcon( QIcon("gui/static/icon_delete_file.png")) self.imageDeleteButton.clicked.connect(self.delete_image) self.videoField = QVideoWidget() self.videoPlayer = QMediaPlayer() # Adjusts settings for the window elements: self.folderField.setDisabled(True) self.folderButton.setIcon(QIcon("gui/static/icon_process_folder.png")) self.folderButton.clicked.connect(self.set_folder) self.processButton.clicked.connect(self.process_files) self.processButton.setFixedWidth(160) self.processButton.setDisabled(True) self.duplicateButton.clicked.connect(self.find_duplicates) self.duplicateButton.setFixedWidth(160) self.reindexButton.clicked.connect(self.reindex_db_data) self.reindexButton.setFixedWidth(160) # prepare tables for images and videos self.imagesTab = self.tableTabs.insertTab(0, self.imageListTable, "Images") self.videosTab = self.tableTabs.insertTab(1, self.videoListTable, "Videos") # images list table setup self.imageListTable.setColumnCount(len(self.COLUMNS_DICT.keys())) self.imageListTable.setHorizontalHeaderLabels(self.COLUMNS_DICT.keys()) self.imageListTable.verticalHeader().setVisible(False) self.imageListTable.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.imageListTable.setSortingEnabled(True) self.imageListTable.cellClicked.connect(self.show_image) # videos list table setup self.videoListTable.setColumnCount(len(self.COLUMNS_DICT.keys())) self.videoListTable.setHorizontalHeaderLabels(self.COLUMNS_DICT.keys()) self.videoListTable.verticalHeader().setVisible(False) self.videoListTable.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.videoListTable.setSortingEnabled(True) self.videoListTable.cellClicked.connect(self.show_video) # set images and videos duplicates columns width self.set_columns_width() # Places the window elements on the window: # Top-left cell of main grid box: subGridBox = QWidget() subGrid = QGridLayout() subGrid.addWidget(self.folderField, 0, 0) subGrid.addWidget(self.folderButton, 0, 1) subGrid.addWidget(self.folderTreeCheckbox, 1, 0) subGrid.addWidget(self.processButton, 2, 0, 1, 2, Qt.AlignCenter) subGrid.addWidget(self.duplicateButton, 3, 0, 1, 2, Qt.AlignCenter) subGrid.addWidget(self.reindexButton, 4, 0, 1, 2, Qt.AlignCenter) subGridBox.setLayout(subGrid) # image data grid box imageGridBox = QWidget() imageGrid = QGridLayout() imageGrid.addWidget(self.imageField, 0, 0, 1, 4, Qt.AlignCenter) # add image buttons imageGrid.addWidget(self.imageCopyButton, 1, 0, 1, 1) imageGrid.addWidget(self.imageViewButton, 1, 1, 1, 1) imageGrid.addWidget(self.imageOpenDirButton, 1, 2, 1, 1) imageGrid.addWidget(self.imageDeleteButton, 1, 3, 1, 1) imageGrid.addWidget(self.imageNameField, 2, 0, 1, 1) imageGrid.addWidget(self.imageParamsField, 2, 3, 1, 1) imageGridBox.setLayout(imageGrid) # Main grid box: self.mainGrid = QGridLayout() self.mainGrid.addWidget(subGridBox, 0, 0) self.mainGrid.addWidget(self.tableTabs, 1, 0) self.mainGrid.addWidget(imageGridBox, 1, 1) self.mainGrid.addWidget(self.videoField, 0, 1, 2, 1) self.mainGrid.setColumnMinimumWidth(0, 400) self.mainGrid.setRowMinimumHeight(1, 600) self.mainGrid.setColumnStretch(1, 1) self.setLayout(self.mainGrid) # Creates a QThread instance: self.thread = ProcessingThread(self.folderField, self.imageListTable, self.videoListTable, self.folderTreeCheckbox) self.thread.finishedTrigger.connect(self.finish_thread) # filling table while first run self.reindex_db_data() # hide image interface self.hide_active_image() def set_columns_width(self): # looping all columns and set with for value in self.COLUMNS_DICT.values(): self.imageListTable.setColumnWidth(value["index"], value["width"]) self.videoListTable.setColumnWidth(value["index"], value["width"]) def reindex_db_data(self): self.duplicateButton.setDisabled(True) self.processButton.setDisabled(True) self.reindexButton.setDisabled(True) # Reindex already exist folders and files; Image and Video files reindex_image_files() reindex_video_files() # run table filling after reindexing self.table_data_init() self.duplicateButton.setEnabled(True) self.processButton.setEnabled(True) self.reindexButton.setEnabled(True) def center_widget_item(self, text: str) -> QTableWidgetItem: # create the item center_align_item = QTableWidgetItem(text) # change the alignment center_align_item.setTextAlignment(Qt.AlignCenter) return center_align_item def table_data_init(self): # get available images from DB with db_session(): images = Image.all() for idx, image in enumerate(images): numRows = self.imageListTable.rowCount() self.imageListTable.insertRow(numRows) str_image_idx = str(idx) IMAGE_PATH_DICT[str_image_idx] = { "id": image.id, "name": image.image_name, "additional_attrs": { "height": image.image_height, "width": image.image_width }, "folder": image.image_path, "type": (image.image_name.split(".")[-1]).lower(), "full_path": image.full_path(), } self.imageListTable.setItem(idx, self.COLUMNS_DICT["ID"]["index"], self.center_widget_item(str_image_idx)) self.imageListTable.setItem( idx, self.COLUMNS_DICT["File name"]["index"], self.center_widget_item(image.image_name), ) self.imageListTable.setItem( idx, self.COLUMNS_DICT["Format"]["index"], self.center_widget_item( IMAGE_PATH_DICT[str_image_idx]["type"]), ) duplicateIcon = QTableWidgetItem() duplicateIcon.setIcon(QIcon("gui/static/icon_view_duplicates.png")) self.imageListTable.setItem(idx, self.COLUMNS_DICT["Dup"]["index"], duplicateIcon) def hide_active_image(self): self.imageField.hide() self.imageCopyButton.hide() self.imageViewButton.hide() self.imageOpenDirButton.hide() self.imageDeleteButton.hide() self.imageNameField.hide() self.imageParamsField.hide() def show_active_image(self): self.imageField.show() self.imageCopyButton.show() self.imageViewButton.show() self.imageOpenDirButton.show() self.imageDeleteButton.show() self.imageNameField.show() self.imageParamsField.show() def open_image_file(self): open_path(path=IMAGE_PATH_DICT[self.active_image_id]["full_path"]) def open_image_path(self): open_path(path=IMAGE_PATH_DICT[self.active_image_id]["folder"]) def delete_image(self): # count image table position image_table_position = list(IMAGE_PATH_DICT.keys()).index( self.active_image_id) message = QMessageBox().question( self, "Confirm deletion", "Delete duplicate media file?", QMessageBox.Yes | QMessageBox.No, ) if message == QMessageBox.Yes: self.imageListTable.removeRow(image_table_position) image_id = IMAGE_PATH_DICT[self.active_image_id]["id"] # run custom delete with db_session(): Image[image_id].custom_delete() # delete image key from dict del IMAGE_PATH_DICT[self.active_image_id] self.hide_active_image() QMessageBox().information(self, "File deletion", "File success deleted", QMessageBox.Ok, QMessageBox.Ok) elif message == QMessageBox.No: pass def copy_image_path(self): try: result = copy_image( IMAGE_PATH_DICT[self.active_image_id]["full_path"]) if result: QMessageBox.information( self, "Copy path", "Success!\nFile copied to clipboard!", QMessageBox.Ok, QMessageBox.Ok, ) else: QMessageBox.warning( self, "Copy path", "Error!\nSorry, i can`t copy image to clipboard.", QMessageBox.Ok, QMessageBox.Ok, ) except Exception: print(traceback.format_exc()) QMessageBox.warning( self, "Copy path", f"Error!\n{traceback.format_exc()}", QMessageBox.Ok, QMessageBox.Ok, ) # Get a folder full of multimedia files to work with def set_folder(self): self.folderPath = QFileDialog.getExistingDirectory(self) if self.folderPath == "": self.folderPath = self.folderField.text() self.folderField.setText(self.folderPath) self.processButton.setEnabled(True) self.statusBar.clearMessage() # Start the thread and fill the table with those files def process_files(self): # set other buttons disabled self.duplicateButton.setDisabled(True) self.reindexButton.setDisabled(True) # Clears both tables upon restarting function: self.imageListTable.clearContents() self.imageListTable.setRowCount(0) self.videoListTable.clearContents() self.videoListTable.setRowCount(0) self.statusBar.setStyleSheet("color: black") self.statusBar.showMessage("Processing...") if self.folderField.text() == "": self.statusBar.setStyleSheet("color: red") self.statusBar.showMessage("Please choose a directory") self.duplicateButton.setEnabled(True) self.reindexButton.setEnabled(True) return None if not self.thread.isRunning(): self.duplicateRefs.clear() self.thread.start() self.processButton.setText("Stop") elif self.thread.isRunning(): self.thread.terminate() self.processButton.setText("Process media files") self.duplicateButton.setEnabled(True) self.reindexButton.setEnabled(True) # Thread done and ded def finish_thread(self): self.statusBar.setStyleSheet("color: black") self.statusBar.showMessage("Finished!") self.processButton.setText("Process media files") # set all buttons able self.duplicateButton.setEnabled(True) self.reindexButton.setEnabled(True) # Start the second thread and remove all unique files from the table def find_duplicates(self): if IMAGE_PATH_DICT == {}: self.statusBar.setStyleSheet("color: red") self.statusBar.showMessage("Please process your media files first") return None self.duplicateButton.setDisabled(True) self.processButton.setDisabled(True) self.reindexButton.setDisabled(True) self.statusBar.setStyleSheet("color: black") self.statusBar.showMessage("Finding duplicates...") with db_session(): # get all images descriptors image_files_query = Image.get_descriptors() pairs_amount = int( len(image_files_query) * (len(image_files_query) - 1) / 2) QMessageBox.information( self, "Find duplicates", f""" Similar images search start. Please wait!\n You have ~{pairs_amount} images pairs; Work will get ~{round(pairs_amount*0.00006, 2)} sec. """, QMessageBox.Ok, QMessageBox.Ok, ) # run function to find duplicates result = feature_description(images_list=image_files_query) with db_session(): # save duplicates to DB save_images_duplicates(result) QMessageBox.information(self, "Find duplicates", "Success!", QMessageBox.Ok, QMessageBox.Ok) # set all buttons able self.duplicateButton.setEnabled(True) self.reindexButton.setEnabled(True) self.processButton.setEnabled(True) # TODO: new thread removing all unique media. Only duplicates remain # Show an image upon clicking its name in the table def show_image(self, row, column): imageId = self.imageListTable.item(row, 0).text() # set new active image id self.active_image_id = imageId # Removes a video from screen if shown: self.videoPlayer.stop() self.videoField.hide() # show active image self.show_active_image() # show image and additional data self.imageNameField.setText(f"{IMAGE_PATH_DICT[imageId]['name']}") self.imageParamsField.setText( f"HxW: {IMAGE_PATH_DICT[imageId]['additional_attrs']['height']}px" + f" x {IMAGE_PATH_DICT[imageId]['additional_attrs']['width']}px") # Shows animated images if IMAGE_PATH_DICT[imageId]["name"].lower().endswith("gif"): gif = QMovie(IMAGE_PATH_DICT[imageId]["full_path"]) gifSize = QSize(*self.smooth_gif_resize( IMAGE_PATH_DICT[imageId]["full_path"], 600, 600)) gif.setScaledSize(gifSize) self.imageField.setMovie(gif) gif.start() # Shows static images else: self.imageField.setPixmap( QPixmap(IMAGE_PATH_DICT[imageId]["full_path"]).scaled( 600, 600, Qt.KeepAspectRatio, Qt.SmoothTransformation)) if column == self.COLUMNS_DICT["Dup"]["index"]: self.duplicateWindow = DuplicateWindow( image_data=IMAGE_PATH_DICT[imageId], raw_id=imageId) if imageId not in self.duplicateRefs.keys(): self.duplicateRefs[imageId] = self.duplicateWindow self.duplicateWindow.show() self.duplicateWindow.closeTrigger.connect(self.delete_reference) # Show a video upon clicking its name in the table def show_video(self, row, column): videoItem = self.videoListTable.item(row, column) videoId = self.videoListTable.item(row, 0).text() self.mainGrid.setColumnMinimumWidth(1, 800) # Prevents from KeyError when clicking the second column: if videoItem.text() == VIDEO_PATH_DICT[videoId][0]: videoItemPath = VIDEO_PATH_DICT[videoId][2] videoContent = QMediaContent(QUrl.fromLocalFile(videoItemPath)) self.videoPlayer.setMedia(videoContent) self.videoPlayer.setVideoOutput(self.videoField) # Removes an image from screen if shown and starts video: self.imageField.clear() self.imageField.hide() self.videoField.show() self.videoPlayer.play() # Remove a previously added reference from a dict if a DuplicateWindow was closed # so it can be opened again def delete_reference(self, itemId): self.duplicateRefs.pop(itemId) # An amazing workaround for gif resizing procedure # because PyQt's native one doesn't work for some reason: def smooth_gif_resize(self, gif, frameWidth, frameHeight): gif = Pil_Image.open(gif) gifWidth0, gifHeight0 = gif.size widthRatio = frameWidth / gifWidth0 heightRatio = frameHeight / gifHeight0 if widthRatio >= heightRatio: gifWidth1 = gifWidth0 * heightRatio gifHeight1 = frameHeight return gifWidth1, gifHeight1 gifWidth1 = frameWidth gifHeight1 = gifHeight0 * widthRatio return gifWidth1, gifHeight1
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() #Load mainwindow.ui from Qt Designer uic.loadUi('../ui/mainwindow.ui', self) #Load all settings self.initMainWindow() #Show the main window self.show() def initMainWindow(self): """ This function initialize all the buttons and all the setting for displaying and control the video. """ self.setWindowIcon( QtGui.QIcon( "../resources/icons/GUI_Icons/1519132568_movavi-video-editor.png" )) #delete all temp files self.deleteAllTemp() self.setWindowTitle("VideoEditor") """<Objects>""" #Object for controling all edit functions self.edit = Panel() """</Objects>""" """--------------------<Global variables>----------------------------""" #Thread manager variable self.threadmanager = True #Audio file holder self.audioFile = '' #frame time variable self.frameTime = '' #frame file path self.frameFilePath = '' #Total number of curent media opened self.totalIndex = -1 #Dictionary for index and path for the media self.curentFiles = {} #Index that indicates the curent media selected self.curentIndex = self.totalIndex #Curent index of Concatenate ListView self.curentIndexOfConcatenateList = -1 #Dictionary with all video path for concatenate self.concatenateVideos = {} #Total number of videos added to the concatenate list view self.totalNrOfVideosConcat = -1 #Media play speed self.speed = 1 # self.subtitlesFileVG = '' """-------------------</Global variables>----------------------------""" """----------------<Media player settings>---------------------------""" #Create a mediaplayer object to control the video self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.mediaPlayer.setVolume(50) #Create a playlist object for multiple videos self.playlist = QMediaPlaylist() self.mediaPlayer.setPlaylist(self.playlist) self.model = PlaylistModel(self.playlist) self.videoFiles.setModel(self.model) self.playlist.currentIndexChanged.connect( self.playlist_position_changed) selection_model = self.videoFiles.selectionModel() selection_model.selectionChanged.connect( self.playlist_selection_changed) #Create videoWidget object for displaying the video videoWidget = QVideoWidget() #videoWidget set self.videoPreviewLayout = QVBoxLayout() self.videoPreviewLayout.addWidget(videoWidget) self.vpfVideoPreview.setLayout(self.videoPreviewLayout) """----------------</Media player settings>--------------------------""" """-----------------<Buttons&Labels settings>-------------------------""" #Create Open Video button in taskbar self.open = QAction('&Open Video', self) self.open.setStatusTip('Open Video') self.menuFiles.addAction(self.open) self.setAcceptDrops(True) #PlayButton self.playButton.setEnabled(False) #Speed label self.speedLabel.setText("1.0x") #Slider settings timeline self.videoTimeSlider.setRange(0, 0) #Slider settings volume self.volume.setRange(0, 100) self.volume.setValue(50) self.volumeTextDisplay.setText("50%") #Cut lock buttons self.lockButtonStart.setCheckable(True) self.lockButtonFinish.setCheckable(True) #Cut text editor settings self.cutStart.setReadOnly(True) self.cutFinish.setReadOnly(True) self.cutStart.setText("0:00:00") self.cutFinish.setText("0:00:00") #Resolution Image settings self.resolutionIcon.setPixmap( QPixmap("../resources/icons/GUI_Icons/720.png")) """-----------------</Buttons&Labels settings>-------------------------""" """-----------------<Buttons connections>------------------------------""" """ -----------<Player buttons>--------- """ #Play button self.playButton.clicked.connect(self.playVideo) #back 15 seconds Button self.skipbackButton.clicked.connect(self.skipbackFunction) #skip 15 seconds forward Button self.skipforwardButton.clicked.connect(self.skipforwadFunction) #fastorForward button self.fastForward.clicked.connect(self.fastForwardFunction) #rewind button self.rewind.clicked.connect(self.rewindFunction) #Add video button self.addButton.clicked.connect(self.openFile) #Remove video button self.deleteButton.clicked.connect(self.RemoveVideo) #save video self.saveVideo.clicked.connect(self.saveVideoFunction) #Time slider self.videoTimeSlider.sliderMoved.connect(self.setPosition) #Volume slider self.volume.sliderMoved.connect(self.volumeControl) #media player change state self.mediaPlayer.stateChanged.connect(self.mediaStateChange) self.mediaPlayer.positionChanged.connect(self.positionChange) self.mediaPlayer.durationChanged.connect(self.durationChange) """ -----------</Player buttons>--------- """ #Open file self.open.triggered.connect(self.openFile) """ -------------<Edit Buttons>----------------- """ """<Concatenate>""" #Create a model for Concatenate Lisview self.concatenateModel = QtGui.QStandardItemModel() #Set the model to the Concatenate List view self.concatenateList.setModel(self.concatenateModel) #Concatenate list of videos self.concatenateList.clicked[QtCore.QModelIndex].connect( self.setConcatenateIndex) #Add button to concatenate list self.addConcatenate.clicked.connect(self.addVideoToConcatenate) # When you receive the signal, you call QtGui.QStandardItemModel.itemFromIndex() # on the given model index to get a pointer to the item self.removeConcatenate.clicked.connect(self.removeVideoToConcatenate) #Concatenate Button self.concatenateButton.clicked.connect(self.concatenateThreadFunction) """</Concatenate>""" """<Cut>""" #Lock cut filed1 self.lockButtonStart.clicked.connect(self.lockButtonChangeIconStart) #Lock cut filed2 self.lockButtonFinish.clicked.connect(self.lockButtonChangeIconFinish) #Cut button self.cutButton.clicked.connect(self.cutThreadFunction) """</Cut>""" """<Resolution>""" #Resoluiton ComboBox for selecting the desired resolution self.ResolutionsList.currentIndexChanged.connect( self.changeResolutionDisplay) #Change resolution button self.changeResolution.clicked.connect(self.changeResolutionThread) """</Resoluton>""" """<Mirror>""" #Mirror button self.mirroringButton.clicked.connect(self.mirrorThread) """</Mirror>""" """<Audio replace>""" self.openAudioFile.clicked.connect(self.openAudio) self.removeAudioFile.clicked.connect(self.removeAudioFileFunction) self.audioModeSelect.currentIndexChanged.connect( self.changeAudioBackground) self.AddAudio.clicked.connect(self.SoundReplaceThread) """</Audio replace>""" """<GetFrame>""" self.getFrameButton.clicked.connect(self.GetFrameFunction) #self.saveFrameButton.setShortcut("Ctrl+S") self.saveFrameButton.setStatusTip('Save File') self.saveFrameButton.clicked.connect(self.saveFrame) """"</GetFrame>""" """<AddSubtitles>""" self.loadSubtitles.clicked.connect(self.loadSubtitlesFunction) self.cleanButton.clicked.connect(self.removeSubtitlesFunction) self.addSubtitle.clicked.connect(self.addSubtitlesThread) """</AddSubtitles>""" """<VideoGrep>""" self.loadSubtitlesVG.clicked.connect(self.loadSubtitlesVideoGrep) self.cleanButtonVideoGrep.clicked.connect( self.removeSubtitlesVideoGrep) self.videoGrep.clicked.connect(self.videoGrepThread) """</VideoGrep>""" """ -------------</Edit Buttons>----------------- """ """ -------------<Shortcut Buttons>--------------- """ self.soundShortcut.clicked.connect(self.soundShortcutKey) self.getFrameShortcut.clicked.connect(self.getFrameShortcutKey) self.cutShortcut.clicked.connect(self.cutShortcutKey) self.concatShortcut.clicked.connect(self.concatShortcutKey) self.mirrorShortcut.clicked.connect(self.mirrorShortcutKey) """ -------------</Shortcut Buttons>--------------- """ """-----------------</Buttons connections>----------------------------""" """-------------------<Threads for editing>--------------------------""" self.pool = QThreadPool() """-------------------</Threads for editing>--------------------------""" """<Experimental>""" qtimeline = QTimeLine(360, 1) self.test = QVBoxLayout() qtimeline2 = QTimeLine(360, 1) self.test.addWidget(qtimeline) self.test.addWidget(qtimeline2) self.sfTimeLineFrame.setLayout(self.test) #self.editMenu.setCurrentIndex(5) """</Experimental>""" #Set output to the video self.mediaPlayer.setVideoOutput(videoWidget) """ ------------------<Concatenate functions>---------------------------""" def setConcatenateIndex(self, index): """ Set the curent index of the selected item from concatenate list view (self.concatenateList) """ #Get the item from the model of index "index" item = self.concatenateModel.itemFromIndex(index) #Get the "item " row index self.curentIndexOfConcatenateList = item.index().row() print(self.concatenateVideos) def addVideoToConcatenate(self): """ Add from 'concatenateVideoList' a video to 'concatenateList' """ try: #Add the current video selected from the ComboBox to the concatenate list view item = QtGui.QStandardItem(self.curentFiles[ self.concatenateVideoList.currentIndex()].split('/')[-1]) self.concatenateModel.appendRow(item) self.totalNrOfVideosConcat += 1 self.concatenateVideos[ self.totalNrOfVideosConcat] = self.curentFiles[ self.concatenateVideoList.currentIndex()] except: print("No video") QMessageBox.about(self, "No video", "Please add a video! ") print(self.concatenateVideoList.currentIndex()) def removeVideoToConcatenate(self): """ Remove video from concatenation list. """ try: self.concatenateModel.removeRow(self.curentIndexOfConcatenateList) del self.concatenateVideos[self.curentIndexOfConcatenateList] self.totalNrOfVideosConcat -= 1 self.SortFilesIndexConcat() except: QMessageBox.about(self, "No video", "No video to remove or not selected! ") print("Error when removing video from list") def concatenate(self): """ This function is used for concatenate multiple videos from the list. """ if (self.curentIndex == -1 and self.totalIndex != -1): self.curentIndex = 0 try: videosToConcatenate = [] #I'm adding the main video videosToConcatenate.append(self.curentFiles[self.curentIndex]) #Add the path to all videos to be concatenated for key in self.concatenateVideos: videosToConcatenate.append(self.concatenateVideos[key]) #Save the current index befor concatenation because #during the concatenation the user could change the curent video #so it would affect curentFiles indexOfRootVideo = self.curentIndex print(videosToConcatenate) #Call concatenate function and save the url of the modified video self.curentFiles[indexOfRootVideo] = self.edit.concat( videosToConcatenate) #Update the media with the edited video self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile("../resources/videos/blackvideo.mp4"))) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile(self.curentFiles[indexOfRootVideo]))) #Clear concatenate list view self.concatenateModel.removeRows(0, self.concatenateModel.rowCount()) #Clear the dict that holds all the data for concatenation self.concatenateVideos.clear() #Reste the number of videos to be concatenated self.totalNrOfVideosConcat = -1 except: print( "A problem occured during concatenation process.Check 'concatenate' function" ) def SortFilesIndexConcat(self): """ This function sort the curentFiles dictionary. When an element is deleted from curentFiles the function sort the index of the curentFiles ascending. """ newIndex = 0 newCurentFiles = {} #loop through the curentFiles and update the index for key in self.concatenateVideos: newCurentFiles[newIndex] = self.concatenateVideos[key] newIndex += 1 #curentFiles files is updated to the new dictionary of files self.concatenateVideos = newCurentFiles.copy() """-------------------</Concatenate functions>--------------------------""" """-----------------------<Cut functions>--------------------------------""" def lockButtonChangeIconStart(self): """ Function for changing the icon when the button is pressed. """ if (self.lockButtonStart.isChecked() == True): self.lockButtonStart.setIcon( QIcon("../resources/icons/GUI_Icons/icons8-lock-80.png")) else: self.lockButtonStart.setIcon( QIcon("../resources/icons/GUI_Icons/icons8-padlock-80.png")) def lockButtonChangeIconFinish(self): """ Function for changing the icon when the button is pressed. """ if (self.lockButtonFinish.isChecked() == True): self.lockButtonFinish.setIcon( QIcon("../resources/icons/GUI_Icons/icons8-lock-80.png")) else: self.lockButtonFinish.setIcon( QIcon("../resources/icons/GUI_Icons/icons8-padlock-80.png")) def restCutButtons(self): """ This function is used to reset all the value for cut section. """ self.cutStart.setText("0:00:00") self.cutFinish.setText("0:00:00") if (self.lockButtonStart.isChecked() == True): self.lockButtonStart.toggle() if (self.lockButtonFinish.isChecked() == True): self.lockButtonFinish.toggle() self.lockButtonChangeIconStart() self.lockButtonChangeIconFinish() def cutFunction(self): """ Function used for cut a video from 'start' to 'finish' and replace in the 'curentFiles'(dictionary that holds all opend video) the curent video path with the path provided by the 'edit.cut' """ try: #if both buttons are pressed the the function can be called if (self.lockButtonStart.isChecked() == True and self.lockButtonFinish.isChecked() == True): try: #save the current index before cut because user can change the 'curentIndex' during execution indexOfRootVideo = self.curentIndex #call the cut function and the result path is saved in currentFiles self.curentFiles[indexOfRootVideo] = self.edit.cut( [self.curentFiles[indexOfRootVideo]], [ self.cutStart.toPlainText(), self.cutFinish.toPlainText() ]) #Set the new video self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( "../resources/videos/blackvideo.mp4"))) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( self.curentFiles[indexOfRootVideo]))) #Reset all values for cut function except: print("Problem in at self.edit.cut or mediaPlayer") except: print("Problem in cutFunction function") """-----------------------</Cut functions>-------------------------------""" """-----------------------<Mirror functions>-----------------------------""" def mirrorVideo(self): if (self.curentIndex == -1 and self.totalIndex != -1): self.curentIndex = 0 try: indexOfRootVideo = self.curentIndex result = '' result = self.edit.video_mirroring( [self.curentFiles[indexOfRootVideo]]) if (result != ''): self.curentFiles[indexOfRootVideo] = result self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( "../resources/videos/blackvideo.mp4"))) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( self.curentFiles[indexOfRootVideo]))) except: print("Problem in change mirror function") """-----------------------</Mirror functions>-----------------------------""" """-----------------------<Resoluton functions>-----------------------------""" def changeResolutionF(self): """ Function for changing the video resolution. """ if (self.curentIndex == -1 and self.totalIndex != -1): self.curentIndex = 0 currentResolution = self.ResolutionsList.currentText( )[0:len(self.ResolutionsList.currentText()) - 1] try: indexOfRootVideo = self.curentIndex self.curentFiles[indexOfRootVideo] = self.edit.video_resize( [self.curentFiles[indexOfRootVideo]], currentResolution) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile("../resources/videos/blackvideo.mp4"))) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile(self.curentFiles[indexOfRootVideo]))) except: print("Problem in change resolution") def changeResolutionDisplay(self): """ Usef for changing image in resolution section when the user select a resolution. """ resolutionsIconList = [ "../resources/icons/GUI_Icons/720.png", "../resources/icons/GUI_Icons/540.png", "../resources/icons/GUI_Icons/360.png", "../resources/icons/GUI_Icons/240.png", "../resources/icons/GUI_Icons/144.png" ] if (self.ResolutionsList.currentIndex() == 0): self.resolutionIcon.setPixmap(QPixmap(resolutionsIconList[0])) elif (self.ResolutionsList.currentIndex() == 1): self.resolutionIcon.setPixmap(QPixmap(resolutionsIconList[1])) elif (self.ResolutionsList.currentIndex() == 2): self.resolutionIcon.setPixmap(QPixmap(resolutionsIconList[2])) elif (self.ResolutionsList.currentIndex() == 3): self.resolutionIcon.setPixmap(QPixmap(resolutionsIconList[3])) elif (self.ResolutionsList.currentIndex() == 4): self.resolutionIcon.setPixmap(QPixmap(resolutionsIconList[4])) """-----------------------</Resoluton functions>--------------------------""" """-----------------------<Sound Repalce functions>--------------------------""" def openAudio(self): try: fileName = QFileDialog.getOpenFileName(self, "Open Audio") mimetypes.init() mimestart = mimetypes.guess_type(fileName[0])[0] if mimestart != None: mimestart = mimestart.split('/')[0] if mimestart == 'audio': print("Audio file detected") self.audioFile = fileName[0] self.audioFileCheck.setIcon( QIcon("../resources/icons/GUI_Icons/check.png")) else: QMessageBox.about( self, "Audio", "This is not an audio file.Please load an audio file.." ) print("Non audio file detected") else: QMessageBox.about(self, "Audio", "This file format is not accepted.") print("Not accepted file") except: QMessageBox.about(self, "Audio", "Changing sound track failed.") print("Problem in open audio function") def removeAudioFileFunction(self): self.audioFile = '' self.audioFileCheck.setIcon( QIcon("../resources/icons/GUI_Icons/ezgif-7-e04c11fb7018.png")) def changeAudioBackground(self): if (self.audioModeSelect.currentIndex() == 0): self.aduioModeImage.setPixmap( QPixmap("../resources/img/soundAdd.png")) elif (self.audioModeSelect.currentIndex() == 1): self.aduioModeImage.setPixmap( QPixmap("../resources/img/soundReplace.png")) def SoundReplaceFunction(self): if (self.curentIndex == -1 and self.totalIndex != -1): self.curentIndex = 0 audioMode = self.audioModeSelect.currentText() print(audioMode) try: if (self.audioFile != ''): if (self.totalIndex != -1): indexOfRootVideo = self.curentIndex self.curentFiles[ indexOfRootVideo] = self.edit.soundReplace( [self.curentFiles[indexOfRootVideo]], self.audioFile, audioMode) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( "../resources/videos/blackvideo.mp4"))) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( self.curentFiles[indexOfRootVideo]))) else: print("No video uploaded") else: print("No aduio file uploaded") except: print("Problem in SoundReplaceFunction") """-----------------------</Sound Repalce functions>-------------------------""" """-----------------------<GetFrame functions>-------------------------""" def GetFrameFunction(self): if (self.curentIndex == -1 and self.totalIndex != -1): self.curentIndex = 0 try: if (self.totalIndex != -1 and self.frameTime != ''): indexOfRootVideo = self.curentIndex print(self.frameTime) self.frameFilePath = '' self.frameFilePath = self.edit.getFrame( [self.curentFiles[indexOfRootVideo]], self.frameTime) self.extractedFrame.setPixmap(QPixmap(self.frameFilePath)) else: print("No video uploaded or frameTime is empty") except: print("Problem in GetFrameFunction") def saveFrame(self): try: fileName = QFileDialog.getSaveFileName(self, 'Save File', "img.jpg", '*.jpg') img = cv2.imread(self.frameFilePath) cv2.imwrite(fileName[0], img) except: QMessageBox.about(self, "Save image", "Problem during saving image.") print("Problem during saving image") """-----------------------</GetFrame functions>-------------------------""" """-----------------------<Add Subtitles functions>-----------------------""" def loadSubtitlesFunction(self): try: fileName = QFileDialog.getOpenFileName(self, "Open Subtitles") if (fileName[0].split('.')[-1] == "srt"): self.subtitlesFile = fileName[0] self.subtitlesCheck.setIcon( QIcon("../resources/icons/GUI_Icons/check.png")) else: QMessageBox.about( self, "Subtitles", "Couldn't load subtitles.Please use file with .srt extension." ) except: print("Problem in load Subtitles function") def removeSubtitlesFunction(self): self.subtitlesFile = '' self.subtitlesCheck.setIcon( QIcon("../resources/icons/GUI_Icons/ezgif-7-e04c11fb7018.png")) def addSubtitlesFunction(self): if (self.curentIndex == -1 and self.totalIndex != -1): self.curentIndex = 0 try: if (self.subtitlesFile != ''): if (self.totalIndex != -1): indexOfRootVideo = self.curentIndex self.curentFiles[ indexOfRootVideo] = self.edit.addSubtitles( [self.curentFiles[indexOfRootVideo]], self.subtitlesFile) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( "../resources/videos/blackvideo.mp4"))) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( self.curentFiles[indexOfRootVideo]))) else: print("No video uploaded") else: print("No subtitles file uploaded") except: print("Problem in addSubtitlesFunction") """-----------------------</Add Subtitles functions>----------------------""" """-----------------------</VideoGrep functions>--------------------------""" def loadSubtitlesVideoGrep(self): try: fileName = QFileDialog.getOpenFileName(self, "Open Subtitles") if (fileName[0].split('.')[-1] == "srt"): self.subtitlesFileVG = fileName[0] self.subtitlesCheckVideoGrep.setIcon( QIcon("../resources/icons/GUI_Icons/check.png")) else: QMessageBox.about( self, "Subtitles", "Couldn't load subtitles.Please use file with .srt extension." ) except: print("Problem in load Subtitles function") def removeSubtitlesVideoGrep(self): self.subtitlesFileVG = '' self.subtitlesCheckVideoGrep.setIcon( QIcon("../resources/icons/GUI_Icons/ezgif-7-e04c11fb7018.png")) def videoGrepFunction(self): try: if (self.subtitlesFileVG != ''): if (self.totalIndex != -1): indexOfRootVideo = self.curentIndex vgMode = self.VGMODE.currentText() if (vgMode == "Clasic"): words = self.vglistSpeciale.toPlainText().split(',') else: words = [ self.firstWord.toPlainText(), self.secondWord.toPlainText() ] self.curentFiles[ indexOfRootVideo] = self.edit.find_sequence( [self.curentFiles[indexOfRootVideo]], words, self.subtitlesFileVG, vgMode) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( "../resources/videos/blackvideo.mp4"))) self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( self.curentFiles[indexOfRootVideo]))) else: print("No video uploaded") else: print("No subtitles file uploaded") except: print("Problem in video Grep Function") """-----------------------</VideoGrep functions>--------------------------""" """--------------------------<File functions>----------------------------""" def openFile(self): """ Function for opening a video file from taskbar. """ fileName = QFileDialog.getOpenFileName(self, "OpenVideo") #Checks if fileName is a valid file if fileName[0] != '': #Set to mediaPlayer object the file(video) self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(fileName[0]))) #Update total number of curent media opened self.totalIndex = self.totalIndex + 1 self.curentIndex = self.totalIndex #Update the curentFiles dict which holds the path for the opened videos self.curentFiles[self.totalIndex] = fileName[0] if (self.totalIndex == 0): self.curentIndex = 0 #Enable the play button after the video was set self.playButton.setEnabled(True) #Add media to the playlist self.playlist.addMedia( QMediaContent(QUrl.fromLocalFile(fileName[0]))) #Add item to the list for avalabile videos for concatenate self.concatenateVideoList.addItem(fileName[0].split('/')[-1]) #A new media was added so we sent a signal to updated List view self.model.layoutChanged.emit() """------------------------</File functions>----------------------------""" """------------------<Media player functions>---------------------------""" def playVideo(self): """" Function for controling the video Play/Pause """ #Checks the state of the video.If the video is playing it will be paused. if self.mediaPlayer.state() == QMediaPlayer.PlayingState: #Pause the video self.mediaPlayer.pause() else: #If the video is paused it will be playing self.mediaPlayer.play() def mediaStateChange(self, ): """ This function is changing the icon of the playButton. If the video is going from playing to "pause",the icon will change to pause icon.Otherwise the playingButton will change to "play" icon """ if self.mediaPlayer.state() == QMediaPlayer.PlayingState: #Change playButton icon into "Pause icon" self.playButton.setIcon( QIcon("../resources/icons/GUI_Icons/002-pause.png")) else: #Change playButton icon into "Play icon" self.playButton.setIcon( QIcon("../resources/icons/GUI_Icons/play.png")) def convert(self, seconds): """ Function for converting duration of the video(seconds) into Hour/minute/seconds and returning that format. """ seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 return "%d:%02d:%02d" % (hour, minutes, seconds) def positionChange(self, position): """ This function is activated when the video is changing the time.When that happens is updating the Time slider the new position and the time label. """ self.videoTimeSlider.setValue(position) #Convert position into seconds duration = position / 1000 self.frameTime = int(duration) self.videoTimeDisplay.setText(self.convert(duration)) if (self.lockButtonStart.isChecked() == False): self.cutStart.setText(self.convert(duration)) if (self.lockButtonFinish.isChecked() == False): self.cutFinish.setText(self.convert(duration)) def durationChange(self, duration): """ This function update the range of the time splider when the video position is changing. """ self.videoTimeSlider.setRange(0, duration) def setPosition(self, position): """ Sets the video time based on time slider. When the user is changing the time slider to a specific time,the video position is updated. """ self.mediaPlayer.setPosition(position) def skipforwadFunction(self): self.mediaPlayer.setPosition(self.mediaPlayer.position() + 15000) def skipbackFunction(self): self.mediaPlayer.setPosition(self.mediaPlayer.position() - 15000) def rewindFunction(self): if (self.speed - 0.1 >= 0.1): self.speed -= 0.1 self.mediaPlayer.setPlaybackRate(self.speed) self.speedLabel.setText(str(round(self.speed, 2)) + "x") def fastForwardFunction(self): if (self.speed + 0.1 <= 2.1): self.speed += 0.1 self.mediaPlayer.setPlaybackRate(self.speed) self.speedLabel.setText(str(round(self.speed, 2)) + "x") def volumeControl(self, volume): """ This function is used for changing the volume of the video and update the volume label.Also,is used to change the color of the slider based on the volume.If is < 50 is green, <50 && < 75 yellow and red for 74 > """ self.volume.setValue(volume) self.mediaPlayer.setVolume(volume) self.volumeTextDisplay.setText(str(volume) + "%") if (volume <= 50): #green self.volume.setStyleSheet(styleSheet.volumeStageOne) elif (volume > 50 and volume <= 75): #yellow self.volume.setStyleSheet(styleSheet.volumeStageTwo) else: #red self.volume.setStyleSheet(styleSheet.volumeStageThree) #If the volume is zero the icon of the volume is changed if (volume == 0): self.volumeIcon.setIcon( QIcon("../resources/icons/GUI_Icons/mute.png")) else: self.volumeIcon.setIcon( QIcon("../resources/icons/GUI_Icons/speaker.png")) def playlist_selection_changed(self, ix): # We receive a QItemSelection from selectionChanged. i = ix.indexes()[0].row() self.playlist.setCurrentIndex(i) self.curentIndex = i self.speed = 1 self.mediaPlayer.setPlaybackRate(self.speed) self.speedLabel.setText(str(self.speed) + "x") try: self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile(self.curentFiles[self.curentIndex]))) #Reset cut text and icon self.restCutButtons() except: print( "Error in playlist_selection_changed function.Media player couldn't be updated" ) def playlist_position_changed(self, i): if i > -1: ix = self.model.index(i) print("playlist_position_changed") self.videoFiles.setCurrentIndex(ix) def RemoveVideo(self): """ This function is connected to the remove button on Project files. It removes the file from List view and curentFiles dictionary.It also changethe mediaPlayer output based on what media was left.If the is media left the video output will be the firs mediaFile from the list.If the List view have no media left,the video output will be an video of 1 seconds with black background to clear the screen. """ if (self.totalIndex != -1): if (self.curentIndex != -1): try: #Delete media from index "curentIndex" self.playlist.removeMedia(self.curentIndex) #Delete video from concatenate ComboBox self.concatenateVideoList.removeItem(self.curentIndex) try: #Delete the file name from index "curentIndex" from curentFiles del self.curentFiles[self.curentIndex] #Decrement the total number of videos opened self.totalIndex = self.totalIndex - 1 #Update index of every video from curentFiles self.SortFilesIndex() if (self.totalIndex == -1): try: self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( "../resources/videos/blackvideo.mp4" ))) #Block the play button self.playButton.setEnabled(False) #Reset the time slider self.videoTimeSlider.setValue(0) #Reset the time slider self.videoTimeSlider.setRange(0, 0) except: print("The black video couldn't be loaded") else: try: self.mediaPlayer.setMedia( QMediaContent( QUrl.fromLocalFile( self.curentFiles[0]))) except: print("The mediaPlayer couldn't be updated") except: print("The value from index " + str(self.curentIndex) + " could not be deleted form curentFiles") except: print("Media cannot be deleted from playlist") else: #Block the play button self.playButton.setEnabled(False) #Reset the time slider self.videoTimeSlider.setValue(0) #Reset the time slider self.videoTimeSlider.setRange(0, 0) def saveVideoFunction(self): try: import shutil extension = self.curentFiles[self.curentIndex].split('.')[-1] extension = "*." + extension fileName = QFileDialog.getSaveFileName(self, 'Save video', "video_name", extension) shutil.move(self.curentFiles[self.curentIndex], fileName[0]) print("Save video Done") except: print("Error during the video saving") def SortFilesIndex(self): """ This function sort the curentFiles dictionary. When an element is deleted from curentFiles the function sort the index of the curentFiles ascending. """ newIndex = 0 newCurentFiles = {} #loop through the curentFiles and update the index for key in self.curentFiles: newCurentFiles[newIndex] = self.curentFiles[key] newIndex += 1 #curentFiles files is updated to the new dictionary of files self.curentFiles = newCurentFiles.copy() def soundShortcutKey(self): self.editMenu.setCurrentIndex(4) def getFrameShortcutKey(self): self.editMenu.setCurrentIndex(5) def cutShortcutKey(self): self.editMenu.setCurrentIndex(1) def concatShortcutKey(self): self.editMenu.setCurrentIndex(0) def mirrorShortcutKey(self): self.editMenu.setCurrentIndex(3) """------------------</Media player functions>-----------------------""" """----------------------<Thread functions>--------------------------""" """---<Concatenate>---""" def concatenateThreadFunction(self): #If is true that means that no thread is running and can start a thread if (self.threadmanager == True): try: #If is false that means that a thread is already executing self.threadmanager = False worker = Worker(self.concatenate) #When the thread is done threadmanager will be True worker.signals.finished.connect(self.ReleaseThread) self.pool.start(worker) except: print("Problem with concatenate thread") else: print("A thread is already running") """---</Concatenate>---""" """---<Cut>---""" def cutThreadFunction(self): if (self.threadmanager == True): try: self.threadmanager = False worker = Worker(self.cutFunction) worker.signals.finished.connect(self.restCutButtons) worker.signals.finished.connect(self.ReleaseThread) self.pool.start(worker) except: print("Problem with cut thread") else: print("A thread is already running") """---</Cut>---""" """---<Resolution>---""" def changeResolutionThread(self): if (self.threadmanager == True): try: self.threadmanager = False worker = Worker(self.changeResolutionF) worker.signals.finished.connect(self.ReleaseThread) self.pool.start(worker) except: print("Problem with resolution thread") else: print("A thread is already running") """---</Resolution>---""" """---<Mirror>---""" def mirrorThread(self): if (self.threadmanager == True): try: self.threadmanager = False worker = Worker(self.mirrorVideo) worker.signals.finished.connect(self.ReleaseThread) self.pool.start(worker) except: print("Problem with mirror thread") else: print("A thread is already running") """---</Mirror>---""" """---<SoundReplace>---""" def SoundReplaceThread(self): if (self.threadmanager == True): try: self.threadmanager = False worker = Worker(self.SoundReplaceFunction) worker.signals.finished.connect(self.ReleaseThread) worker.signals.finished.connect(self.removeAudioFileFunction) self.pool.start(worker) except: print("Problem with SoundReplace thread") else: print("A thread is already running") """---</SoundReplace>---""" def ReleaseThread(self): self.threadmanager = True print(self.curentFiles) """---<GetFrame>---""" def GetFrameThread(self): if (self.threadmanager == True): try: self.threadmanager = False worker = Worker(self.GetFrameFunction) worker.signals.finished.connect(self.ReleaseThread) self.pool.start(worker) except: print("Problem with getFrame thread") else: print("A thread is already running") """---</GetFrame>---""" """---<AddSubtitles>---""" def addSubtitlesThread(self): if (self.threadmanager == True): try: self.threadmanager = False worker = Worker(self.addSubtitlesFunction) worker.signals.finished.connect(self.ReleaseThread) worker.signals.finished.connect(self.removeSubtitlesFunction) self.pool.start(worker) except: print("Problem with add subtitles thread") else: print("A thread is already running") """---</AddSubtitles>--""" """---</VideoGrep>--""" def videoGrepThread(self): if (self.threadmanager == True): try: self.threadmanager = False worker = Worker(self.videoGrepFunction) worker.signals.finished.connect(self.ReleaseThread) worker.signals.finished.connect(self.removeSubtitlesVideoGrep) self.pool.start(worker) except: print("Problem with VideoGrep thread") else: print("A thread is already running") """---</VideoGrep>--""" """---------------------</Thread functions>--------------------------""" def deleteAllTemp(self): import os, shutil folder = ProjectFolders.tmpDir for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) def closeEvent(self, event): """ Popup a dialog when the user is trying to close the main app. """ reply = QMessageBox.question( self, 'Window Close', 'Are you sure you want to close the window?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: if (self.threadmanager == True): try: self.threadmanager = False worker = Worker(self.deleteAllTemp) worker.signals.finished.connect(self.ReleaseThread) self.pool.start(worker) except: print("Problem with getFrame thread") else: print("A thread is already running") event.accept() print('Window closed') else: event.ignore()
class appWindows(QWidget): def __init__(self): super().__init__() self.title = 'Gait Recognition' self.left = 50 self.top = 50 self.width = 1280 self.height = 720 self.file_name = '' self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.setWindowIcon(QIcon(os.getcwd() + "\\gait_logo.jpg")) """ TextBox """ textBox = QLineEdit() """ Video Widget """ video_widget = QVideoWidget() """ Close Button """ close_button = QPushButton("Close", self) close_button.setToolTip("Click to Close Window") close_button.clicked.connect(self.display_message_box) """ Select Video Button """ select_video_button = QPushButton("Select File", self) select_video_button.setToolTip("Choose File") select_video_button.clicked.connect(self.choose_file) """ Predict """ predict_button = QPushButton("Predict", self) predict_button.clicked.connect(self.start_prediction) """ Give Layout to Boxes """ hbox = QHBoxLayout() hbox.addWidget(select_video_button) hbox.addWidget(predict_button) hbox.addWidget(close_button) mainlayout = QVBoxLayout() mainlayout.addWidget(video_widget) mainlayout.addWidget(textBox) mainlayout.addLayout(hbox) self.setLayout(mainlayout) self.mediaPlayer.setVideoOutput(video_widget) self.show() def display_message_box(self): reply = QMessageBox.question(self, "Close Message", "Do you want to quit ?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.close() def close_window(self): QCoreApplication.instance().quit() def choose_file(self): file_name, _ = QFileDialog.getOpenFileName(self, "Open File") if file_name != '': self.file_name = file_name self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(file_name))) def start_prediction(self): file_n = self.file_name print(file_n) if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play()
class App(QMainWindow): def __init__(self): super().__init__() self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.title = 'Flare' self.left = 300 self.top = 300 self.width = 300 self.height = 150 self.color = 0 # 0- toggle to dark 1- toggle to light self.userAction = -1 # 0- stopped, 1- playing 2-paused self.initUI() def initUI(self): # Add file menu menubar = self.menuBar() filemenu = menubar.addMenu('File') windowmenu = menubar.addMenu('Window') fileAct = QAction('Open File', self) folderAct = QAction('Open Folder', self) themeAct = QAction('Toggle light/dark theme', self) fileAct.setShortcut('Ctrl+O') folderAct.setShortcut('Ctrl+D') themeAct.setShortcut('Ctrl+T') filemenu.addAction(fileAct) filemenu.addAction(folderAct) windowmenu.addAction(themeAct) fileAct.triggered.connect(self.openFile) folderAct.triggered.connect(self.addFiles) themeAct.triggered.connect(self.toggleColors) self.addControls() self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.toggleColors() self.show() def addControls(self): wid = QWidget(self) self.setCentralWidget(wid) # Add song controls volumeslider = QSlider(Qt.Horizontal, self) volumeslider.setFocusPolicy(Qt.NoFocus) volumeslider.valueChanged[int].connect(self.changeVolume) volumeslider.setValue(100) playBtn = QPushButton('Play') # play button pauseBtn = QPushButton('Pause') # pause button stopBtn = QPushButton('Stop') # stop button # Add playlist controls prevBtn = QPushButton('Prev') shuffleBtn = QPushButton('Shuffle') nextBtn = QPushButton('Next') # Add button layouts controlArea = QVBoxLayout() # centralWidget controls = QHBoxLayout() playlistCtrlLayout = QHBoxLayout() # Add buttons to song controls layout controls.addWidget(playBtn) controls.addWidget(pauseBtn) controls.addWidget(stopBtn) # Add buttons to playlist controls layout playlistCtrlLayout.addWidget(prevBtn) playlistCtrlLayout.addWidget(shuffleBtn) playlistCtrlLayout.addWidget(nextBtn) # Add to vertical layout controlArea.addWidget(volumeslider) controlArea.addLayout(controls) controlArea.addLayout(playlistCtrlLayout) wid.setLayout(controlArea) # Connect each signal to their appropriate function playBtn.clicked.connect(self.playhandler) pauseBtn.clicked.connect(self.pausehandler) stopBtn.clicked.connect(self.stophandler) prevBtn.clicked.connect(self.prevSong) shuffleBtn.clicked.connect(self.shufflelist) nextBtn.clicked.connect(self.nextSong) self.statusBar() self.playlist.currentMediaChanged.connect(self.songChanged) def openFile(self): song = QFileDialog.getOpenFileName( self, "Open Song", "~", "Sound Files (*.mp3 *.ogg *.wav *.m4a)") if song[0] != '': url = QUrl.fromLocalFile(song[0]) if self.playlist.mediaCount() == 0: self.playlist.addMedia(QMediaContent(url)) self.player.setPlaylist(self.playlist) self.player.play() self.userAction = 1 else: self.playlist.addMedia(QMediaContent(url)) def addFiles(self): if self.playlist.mediaCount() != 0: self.folderIterator() else: self.folderIterator() self.player.setPlaylist(self.playlist) self.player.playlist().setCurrentIndex(0) self.player.play() self.userAction = 1 def folderIterator(self): folderChosen = QFileDialog.getExistingDirectory( self, 'Open Music Folder', '~') if folderChosen != None: it = QDirIterator(folderChosen) it.next() while it.hasNext(): if it.fileInfo().isDir() == False and it.filePath() != '.': fInfo = it.fileInfo() if fInfo.suffix() in ('mp3', 'ogg', 'wav', 'm4a'): self.playlist.addMedia( QMediaContent(QUrl.fromLocalFile(it.filePath()))) it.next() if it.fileInfo().isDir() == False and it.filePath() != '.': fInfo = it.fileInfo() if fInfo.suffix() in ('mp3', 'ogg', 'wav', 'm4a'): self.playlist.addMedia( QMediaContent(QUrl.fromLocalFile(it.filePath()))) def playhandler(self): if self.playlist.mediaCount() == 0: self.openFile() elif self.playlist.mediaCount() != 0: self.player.play() self.userAction = 1 def pausehandler(self): self.userAction = 2 self.player.pause() def stophandler(self): self.userAction = 0 self.player.stop() self.playlist.clear() self.statusBar().showMessage("Stopped and cleared playlist") def changeVolume(self, value): self.player.setVolume(value) def prevSong(self): if self.playlist.mediaCount() == 0: self.openFile() elif self.playlist.mediaCount() != 0: self.player.playlist().previous() def shufflelist(self): self.playlist.shuffle() def nextSong(self): if self.playlist.mediaCount() == 0: self.openFile() elif self.playlist.mediaCount() != 0: self.player.playlist().next() def songChanged(self, media): if not media.isNull(): url = media.canonicalUrl() self.statusBar().showMessage(url.fileName()) def toggleColors(self): """ Fusion dark palette from https://gist.github.com/QuantumCD/6245215. Modified by me and J.J. """ app.setStyle("Fusion") palette = QPalette() if self.color == 0: palette.setColor(QPalette.Window, QColor(53, 53, 53)) palette.setColor(QPalette.WindowText, Qt.white) palette.setColor(QPalette.Base, QColor(25, 25, 25)) palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53)) palette.setColor(QPalette.ToolTipBase, Qt.white) palette.setColor(QPalette.ToolTipText, Qt.white) palette.setColor(QPalette.Text, Qt.white) palette.setColor(QPalette.Button, QColor(53, 53, 53)) palette.setColor(QPalette.ButtonText, Qt.white) palette.setColor(QPalette.BrightText, Qt.red) palette.setColor(QPalette.Link, QColor(235, 101, 54)) palette.setColor(QPalette.Highlight, QColor(235, 101, 54)) palette.setColor(QPalette.HighlightedText, Qt.black) app.setPalette(palette) self.color = 1 elif self.color == 1: palette.setColor(QPalette.Window, Qt.white) palette.setColor(QPalette.WindowText, Qt.black) palette.setColor(QPalette.Base, QColor(240, 240, 240)) palette.setColor(QPalette.AlternateBase, Qt.white) palette.setColor(QPalette.ToolTipBase, Qt.white) palette.setColor(QPalette.ToolTipText, Qt.white) palette.setColor(QPalette.Text, Qt.black) palette.setColor(QPalette.Button, Qt.white) palette.setColor(QPalette.ButtonText, Qt.black) palette.setColor(QPalette.BrightText, Qt.red) palette.setColor(QPalette.Link, QColor(66, 155, 248)) palette.setColor(QPalette.Highlight, QColor(66, 155, 248)) palette.setColor(QPalette.HighlightedText, Qt.black) app.setPalette(palette) self.color = 0
def __init__(self, weight_path, out_file_path, real_time_show_predict_flag: bool, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.setWindowTitle( "Intelligent Monitoring System of Construction Site Software " + CODE_VER) self.showMaximized() '''按键绑定''' # 输入媒体 self.import_media_pushButton.clicked.connect(self.import_media) # 导入 self.start_predict_pushButton.clicked.connect( self.predict_button_click) # 开始推理 # 输出媒体 self.open_predict_file_pushButton.clicked.connect( self.open_file_in_browser) # 文件中显示推理视频 # 下方 self.play_pushButton.clicked.connect( self.play_pause_button_click) # 播放 self.pause_pushButton.clicked.connect( self.play_pause_button_click) # 暂停 self.button_dict = dict() self.button_dict.update({ "import_media_pushButton": self.import_media_pushButton, "start_predict_pushButton": self.start_predict_pushButton, "open_predict_file_pushButton": self.open_predict_file_pushButton, "play_pushButton": self.play_pushButton, "pause_pushButton": self.pause_pushButton, "real_time_checkBox": self.real_time_checkBox }) '''媒体流绑定输出''' self.input_player = QMediaPlayer() # 媒体输入的widget self.input_player.setVideoOutput(self.input_video_widget) self.input_player.positionChanged.connect( self.change_slide_bar) # 播放进度条 self.output_player = QMediaPlayer() # 媒体输出的widget self.output_player.setVideoOutput(self.output_video_widget) '''初始化GPU chart''' self.series = QSplineSeries() self.chart_init() '''初始化GPU定时查询定时器''' # 使用QTimer,0.5秒触发一次,更新数据 self.timer = QTimer(self) self.timer.timeout.connect(self.draw_gpu_info_chart) self.timer.start(1000) # 播放时长, 以 input 的时长为准 self.video_length = 0 self.out_file_path = out_file_path # 推理使用另外一线程 self.predict_handler_thread = PredictHandlerThread( self.input_player, self.output_player, self.out_file_path, weight_path, self.predict_info_plainTextEdit, self.predict_progressBar, self.fps_label, self.button_dict, self.input_media_tabWidget, self.output_media_tabWidget, self.input_real_time_label, self.output_real_time_label, real_time_show_predict_flag) self.weight_label.setText( f" Using weight : ****** {Path(weight_path[0]).name} ******") # 界面美化 self.gen_better_gui() self.media_source = "" # 推理媒体的路径 self.predict_progressBar.setValue(0) # 进度条归零 '''check box 绑定''' self.real_time_checkBox.stateChanged.connect( self.real_time_checkbox_state_changed) self.real_time_checkBox.setChecked(real_time_show_predict_flag) self.real_time_check_state = self.real_time_checkBox.isChecked()
def __init__(self, parent=None): super(MediaControler, self).__init__(parent) self.state = QMediaPlayer.State() self.muted = False self.layout = QVBoxLayout(self) self.up_layout = QHBoxLayout(self) self.remaining_time_label = QLabel(self) self.remaining_time_label.setText("--:--") self.up_layout.addWidget(self.remaining_time_label) self.evolution_slider = QSlider(Qt.Qt.Horizontal, self) self.evolution_slider.setRange(0, 100) self.up_layout.addWidget(self.evolution_slider) self.total_time_label = QLabel(self) self.total_time_label.setText("--:--") self.up_layout.addWidget(self.total_time_label) self.layout.addLayout(self.up_layout) self.sub_layout = QHBoxLayout(self) self.play_button = QToolButton(self) self.play_button.setMinimumSize(36, 36) self.play_button.setIcon(self.style().standardIcon( QStyle.SP_MediaPlay)) self.sub_layout.addWidget(self.play_button) self.backward_button = QToolButton(self) self.backward_button.setIcon(self.style().standardIcon( QStyle.SP_MediaSkipBackward)) self.sub_layout.addWidget(self.backward_button) self.stop_button = QToolButton(self) self.stop_button.setIcon(self.style().standardIcon( QStyle.SP_MediaStop)) self.sub_layout.addWidget(self.stop_button) self.forward_button = QToolButton(self) self.forward_button.setIcon(self.style().standardIcon( QStyle.SP_MediaSkipForward)) self.sub_layout.addWidget(self.forward_button) self.full_screen_button = QToolButton(self) # self.full_screen_button.setCheckable(True) self.full_screen_button.setToolTip("Afficher en mode plein ecran") self.full_screen_button.setIcon(self.style().standardIcon( QStyle.SP_DesktopIcon)) self.sub_layout.addWidget(self.full_screen_button) self.mute_button = QToolButton(self) self.mute_button.setIcon(self.style().standardIcon( QStyle.SP_MediaVolume)) self.sub_layout.addWidget(self.mute_button) self.volume_slider = QSlider(Qt.Qt.Horizontal, self) self.volume_slider.setRange(0, 100) self.volume_slider.setSingleStep(1) self.volume_slider.setMaximumWidth(100) self.sub_layout.addWidget(self.volume_slider) self.volume_label = QLabel(self) self.volume_label.setText("0%") self.sub_layout.addWidget(self.volume_label) spacerItem = QSpacerItem(40, 10, QSizePolicy.Expanding, QSizePolicy.Minimum) self.sub_layout.addItem(spacerItem) self.layout.addLayout(self.sub_layout) self.setStyleSheet(""" QFrame { background-color: beige; border: 1px solid grey; } """) self.setMaximumHeight(80) self.play_button.clicked.connect(self.play) self.stop_button.clicked.connect(self.stop) self.volume_slider.valueChanged.connect(self.update_volume) self.mute_button.clicked.connect(self.set_muted)
class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle("PyQt5 Media Player") self.setGeometry(350, 100, 700, 500) self.setWindowIcon(QIcon('player.png')) p = self.palette() p.setColor(QPalette.Window, Qt.black) self.setPalette(p) self.init_ui() self.show() def init_ui(self): #create media player object self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) #create videowidget object videowidget = QVideoWidget() #create open button openBtn = QPushButton('Open Video') openBtn.clicked.connect(self.open_file) #create button for playing self.playBtn = QPushButton() self.playBtn.setEnabled(False) self.playBtn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playBtn.clicked.connect(self.play_video) #create slider self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, 0) self.slider.sliderMoved.connect(self.set_position) #create label self.label = QLabel() self.label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) #create hbox layout hboxLayout = QHBoxLayout() hboxLayout.setContentsMargins(0, 0, 0, 0) #set widgets to the hbox layout hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.slider) #create vbox layout vboxLayout = QVBoxLayout() vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout) vboxLayout.addWidget(self.label) self.setLayout(vboxLayout) self.mediaPlayer.setVideoOutput(videowidget) #media player signals self.mediaPlayer.stateChanged.connect(self.mediastate_changed) self.mediaPlayer.positionChanged.connect(self.position_changed) self.mediaPlayer.durationChanged.connect(self.duration_changed) def open_file(self): filename, _ = QFileDialog.getOpenFileName(self, "Open Video") if filename != '': self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(filename))) self.playBtn.setEnabled(True) def play_video(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() def mediastate_changed(self, state): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playBtn.setIcon(self.style().standardIcon( QStyle.SP_MediaPause)) else: self.playBtn.setIcon(self.style().standardIcon( QStyle.SP_MediaPlay)) #pause icon display def position_changed(self, position): self.slider.setValue(position) def duration_changed(self, duration): self.slider.setRange(0, duration) def set_position(self, position): self.mediaPlayer.setPosition(position) #getting error if exist def handle_errors(self): self.playBtn.setEnabled(False) self.label.setText("Error: " + self.mediaPlayer.errorString())
def create_gui(self): """ Yep, creates the GUI. """ total_cats = len(self.categories) btn_height, btn_width = 70, self.width / total_cats self.btns = [0] * total_cats # add the category - movies and sports - buttons for i in range(0, total_cats): self.btns[i] = QPushButton(self.categories[i], self) self.btns[i].clicked.connect(self.update_list) self.btns[i].setGeometry(i * btn_width, 0, btn_width, btn_height) # add the side bar that containes use-cases list_width, list_height = 200, 300 self.list = QListWidget(self) self.list.clicked.connect(self.process_use_case) self.list.setGeometry(0, btn_height, list_width, list_height) # add more buttons self.file_btn = QPushButton("Choose file", self) self.file_btn.clicked.connect(self.set_file) self.file_btn.setGeometry(0, list_height + btn_height, list_width, self.height - (list_height + btn_height)) op_btn_height = (self.height - (list_height + btn_height)) / 2 op_btn_width = list_width * 3 / 4 op_btn1 = QPushButton("Find FabBits", self) op_btn1.clicked.connect(self.find_fabbits) op_btn1.setGeometry(self.width - list_width * 3 / 4, list_height + btn_height, op_btn_width, op_btn_height) op_btn2 = QPushButton("Save FabBits", self) op_btn2.clicked.connect(self.save_fabbits) op_btn2.setGeometry(self.width - list_width * 3 / 4, list_height + btn_height + op_btn_height, op_btn_width, op_btn_height) self.status_bar = QPlainTextEdit(self) self.status_bar.setReadOnly(True) self.status_bar.setGeometry(list_width, list_height + btn_height, self.width - list_width - op_btn_width, 2 * op_btn_height) self.original_stream = sys.stdout play_button_h, play_button_w = 30, 30 vw = QVideoWidget(self) vw.setGeometry( list_width, btn_height, self.width - list_width, self.height - btn_height - 2 * op_btn_height - play_button_h) self.media_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.media_player.setVideoOutput(vw) self.media_player.stateChanged.connect(self.state_change) self.media_player.positionChanged.connect(self.set_pos_player) self.media_player.durationChanged.connect(self.set_duration) self.vid_button = QPushButton(self) self.vid_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.vid_button.clicked.connect(self.play_vid) self.vid_button.setEnabled(False) self.vid_button.setGeometry( list_width, self.height - 2 * op_btn_height - play_button_h, play_button_w, play_button_h) self.vid_slider = QSlider(QtCore.Qt.Horizontal, self) self.vid_slider.sliderMoved.connect(self.set_pos_slider) self.stylesheet = """ QSlider::handle { background: qlineargradient( x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f ); border: 1px solid #5c5c5c; width : 10px; margin : -2px 0; border-radius : 3px; } QSlider::groove { background : black; } """ self.vid_slider.setStyleSheet(self.stylesheet) self.vid_slider.setGeometry( list_width + play_button_w, self.height - 2 * op_btn_height - play_button_h, self.width + list_width - play_button_w, play_button_h) self.update_list("MOVIES") self.setWindowTitle('FabBits') self.setFixedSize(self.width, self.height) self.show()
class DotWindow(QWidget): def __init__(self): super().__init__() self.update_timer = QTimer() self.update_timer.timeout.connect(self.updateValues) self.x = (SCREEN_WIDTH - DOT_RADIUS) / 2 self.y = (SCREEN_HEIGHT) / 2 - DOT_RADIUS self.setAutoFillBackground(True) p = self.palette() p.setColor(self.backgroundRole(), Qt.black) self.setPalette(p) if not path.exists(FILENAME0): print("\nFile '{}' doesn't exist!".format(FILENAME0)) quit() self.audio = QMediaPlayer(None) self.audio.setMedia(QMediaContent(QUrl.fromLocalFile(FILENAME0))) def start(self): info_message( QMessageBox.Information, 'Instruction', 'In this part of the experiment, you will see a red dot moving on a black screen. You need to follow the red dot with your eyes without moving your head.\n\nNote: If you want to exit the experiment before the end, click the "Exit the experiment" buttom at the bottom of the screen.' ) self.audio.play() self.start_time = time.time() self.update_timer.start(UPDATE_TIME) def paintEvent(self, event): qp = QPainter(self) qp.setPen(QPen(Qt.red, 0, Qt.SolidLine)) qp.setBrush(QBrush(Qt.red, Qt.SolidPattern)) qp.drawEllipse(self.x, self.y, DOT_RADIUS, DOT_RADIUS) def updateValues(self): elapsed_time = time.time() - self.start_time if elapsed_time < EXP_TIME: self.x = DOT_RADIUS + (SCREEN_WIDTH - 3 * DOT_RADIUS) / 2 * ( 1 - math.sin(6.28318530718 * FREQUENCY * elapsed_time)) self.update() else: self.end_of_dot() def exit_confirmation(self): #asking confirmation to stop the simulation self.audio.pause() self.update_timer.stop() waisted_time_start = time.time() returnValue = exit_question_message() if returnValue == QMessageBox.Yes: info_message(QMessageBox.Information, 'Experiment termination', 'The experiment has been stopped by the user') quit() else: self.update_timer.start(UPDATE_TIME) self.start_time += time.time() - waisted_time_start self.audio.play() def end_of_dot(self): #the end of the simulation self.update_timer.stop() self.audio.pause() info_message(QMessageBox.Information, 'The end of the simulation', 'The simulation has finished') experiment.next_in_scenario()
class Ui_Dialog(QWidget): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(975, 558) Dialog.setStyleSheet("background-color: rgb(0, 85, 255);\n" "background-color: rgb(255, 170, 0);") self.checkBox = QtWidgets.QCheckBox(Dialog) self.checkBox.setGeometry(QtCore.QRect(10, 300, 81, 21)) self.checkBox.setMinimumSize(QtCore.QSize(81, 0)) self.checkBox.setMaximumSize(QtCore.QSize(81, 21)) font = QtGui.QFont() font.setPointSize(8) self.checkBox.setFont(font) self.checkBox.setObjectName("checkBox") self.checkBox_2 = QtWidgets.QCheckBox(Dialog) self.checkBox_2.setGeometry(QtCore.QRect(10, 340, 81, 20)) self.checkBox_2.setObjectName("checkBox_2") self.checkBox_3 = QtWidgets.QCheckBox(Dialog) self.checkBox_3.setGeometry(QtCore.QRect(10, 380, 81, 20)) self.checkBox_3.setObjectName("checkBox_3") self.checkBox_4 = QtWidgets.QCheckBox(Dialog) self.checkBox_4.setGeometry(QtCore.QRect(10, 420, 81, 20)) self.checkBox_4.setObjectName("checkBox_4") self.checkBox_5 = QtWidgets.QCheckBox(Dialog) self.checkBox_5.setGeometry(QtCore.QRect(10, 460, 81, 20)) self.checkBox_5.setObjectName("checkBox_5") self.checkBox_6 = QtWidgets.QCheckBox(Dialog) self.checkBox_6.setGeometry(QtCore.QRect(10, 500, 81, 20)) self.checkBox_6.setObjectName("checkBox_6") self.line_2 = QtWidgets.QFrame(Dialog) self.line_2.setGeometry(QtCore.QRect(0, 59, 981, 21)) font = QtGui.QFont() font.setPointSize(7) font.setBold(False) font.setWeight(50) self.line_2.setFont(font) self.line_2.setFrameShape(QtWidgets.QFrame.HLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName("line_2") self.pushButton = QtWidgets.QPushButton(Dialog) self.pushButton.setGeometry(QtCore.QRect(120, 297, 93, 31)) self.pushButton.setStyleSheet("background-color: rgb(255, 255, 255);") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(Dialog) self.pushButton_2.setGeometry(QtCore.QRect(120, 340, 93, 28)) self.pushButton_2.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(Dialog) self.pushButton_3.setGeometry(QtCore.QRect(120, 380, 93, 28)) self.pushButton_3.setStyleSheet( "background-color: rgb(255, 255, 255);\n" "\n" "") self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(Dialog) self.pushButton_4.setGeometry(QtCore.QRect(120, 420, 93, 28)) self.pushButton_4.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_4.setObjectName("pushButton_4") self.pushButton_5 = QtWidgets.QPushButton(Dialog) self.pushButton_5.setGeometry(QtCore.QRect(120, 460, 93, 28)) self.pushButton_5.setStyleSheet( "background-color: rgb(255, 255, 255);\n" "") self.pushButton_5.setObjectName("pushButton_5") self.pushButton_6 = QtWidgets.QPushButton(Dialog) self.pushButton_6.setGeometry(QtCore.QRect(120, 500, 93, 28)) self.pushButton_6.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_6.setObjectName("pushButton_6") self.line = QtWidgets.QFrame(Dialog) self.line.setGeometry(QtCore.QRect(213, 70, 20, 501)) font = QtGui.QFont() font.setPointSize(7) font.setBold(False) font.setWeight(50) self.line.setFont(font) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.pushButton_7 = QtWidgets.QPushButton(Dialog) self.pushButton_7.setGeometry(QtCore.QRect(10, 100, 201, 28)) self.pushButton_7.setStyleSheet( "background-color: qradialgradient(spread:repeat, cx:0.5, cy:0.5, radius:0.077, fx:0.5, fy:0.5, stop:0 rgba(0, 169, 255, 147), stop:0.497326 rgba(0, 0, 0, 147), stop:1 rgba(0, 169, 255, 147));\n" "background-color: rgb(255, 255, 255);") self.pushButton_7.setObjectName("pushButton_7") self.pushButton_7.clicked.connect(self.open_file) self.pushButton_8 = QtWidgets.QPushButton(Dialog) self.pushButton_8.setGeometry(QtCore.QRect(10, 160, 201, 28)) self.pushButton_8.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_8.setObjectName("pushButton_8") self.line_3 = QtWidgets.QFrame(Dialog) self.line_3.setGeometry(QtCore.QRect(230, 510, 741, 16)) self.line_3.setFrameShape(QtWidgets.QFrame.HLine) self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_3.setObjectName("line_3") self.pushButton_9 = QtWidgets.QPushButton(Dialog) self.pushButton_9.setGeometry(QtCore.QRect(450, 520, 131, 28)) self.pushButton_9.setStyleSheet( "background-color: rgb(255, 255, 255);") self.pushButton_9.setObjectName("pushButton_9") self.pushButton_9.clicked.connect(self.play_video) self.pushButton_10 = QtWidgets.QPushButton(Dialog) self.pushButton_10.setGeometry(QtCore.QRect(730, 520, 93, 28)) self.pushButton_10.setStyleSheet( "background-color: rgb(255, 255, 255);\n" "border-color: rgb(0, 0, 0);") self.pushButton_10.setObjectName("pushButton_10") self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(470, 20, 141, 31)) font = QtGui.QFont() font.setFamily("MS Sans Serif") font.setPointSize(17) font.setBold(True) font.setItalic(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName("label") self.frame = QtWidgets.QFrame(Dialog) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.frame.setGeometry(QtCore.QRect(260, 90, 151, 101)) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName("frame") self.video1 = QVideoWidget(self.frame) self.video1.setGeometry(QtCore.QRect(0, 0, 121, 101)) self.video1.setStyleSheet("background-color: rgb(0, 0, 0);") self.video1.setObjectName("video1") self.pushButton_7.raise_() self.checkBox.raise_() self.checkBox_2.raise_() self.checkBox_3.raise_() self.checkBox_4.raise_() self.checkBox_5.raise_() self.checkBox_6.raise_() self.line_2.raise_() self.pushButton.raise_() self.pushButton_2.raise_() self.pushButton_3.raise_() self.pushButton_4.raise_() self.pushButton_5.raise_() self.pushButton_6.raise_() self.line.raise_() self.pushButton_8.raise_() self.line_3.raise_() self.pushButton_9.raise_() self.pushButton_10.raise_() self.label.raise_() self.frame.raise_() self.mediaPlayer.setVideoOutput(self.video1) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.checkBox.setText(_translate("Dialog", "method 1")) self.checkBox_2.setText(_translate("Dialog", "method 2")) self.checkBox_3.setText(_translate("Dialog", "method 3")) self.checkBox_4.setText(_translate("Dialog", "method 4")) self.checkBox_5.setText(_translate("Dialog", "method 5")) self.checkBox_6.setText(_translate("Dialog", "method 6")) self.pushButton.setText(_translate("Dialog", "DEMO")) self.pushButton_2.setText(_translate("Dialog", "DEMO")) self.pushButton_3.setText(_translate("Dialog", "DEMO")) self.pushButton_4.setText(_translate("Dialog", "DEMO")) self.pushButton_5.setText(_translate("Dialog", "DEMO")) self.pushButton_6.setText(_translate("Dialog", "DEMO")) self.pushButton_7.setText(_translate("Dialog", "Browse Input Video")) self.pushButton_8.setText( _translate("Dialog", "Browse ground frame image")) self.pushButton_9.setText(_translate("Dialog", "Play selected video")) self.pushButton_10.setText(_translate("Dialog", "Close")) self.label.setText(_translate("Dialog", "VIDEO")) self.mediaPlayer.setVideoOutput(self.video1) self.mediaPlayer.stateChanged.connect(self.mediastate_changed) # self.mediaPlayer.positionChanged.connect(self.position_changed) # self.mediaPlayer.durationChanged.connect(self.duration_changed) def open_file(self): filename, _ = QFileDialog.getOpenFileName(self, "Open Video") if filename != '': self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(filename))) self.pushButton_9.setEnabled(True) def play_video(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() def mediastate_changed(self, state): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.pushButton_9.setIcon(self.style().standardIcon( QStyle.SP_MediaPause)) else: self.pushButton_9.setIcon(self.style().standardIcon( QStyle.SP_MediaPlay)) def handle_errors(self): self.pushButton_9.setEnabled(False) self.label.setText("Error: " + self.mediaPlayer.errorString())
class Ui_selectVideo(object): def openFtoAWindow(self): self.Window = QtWidgets.QWidget() self.ui = addFaceToAnalyze.AFTA_Ui_Form() self.ui.setupUi(self.Window) self.ui.getVideo(video=self.video) self.Window.show() self.widget.hide() def getVideo(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(None, "Select Video", options=options) if fileName: '''vidcap = cv2.VideoCapture(fileName) total = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)) num = total/2 vidcap.set(cv2.CAP_PROP_POS_MSEC,num) success,image = vidcap.read()''' shortenedFileName = self.getShortenedFilename(fileName) self.movieImageLabel.setPixmap(QtGui.QPixmap()) self.movieImageLabel.clear() self.movieImageLabel.setGeometry(QtCore.QRect(140, 240, 201, 201)) self.movieImageLabel.setStyleSheet("border: 1px solid black;") self.movieImageLabel.setAlignment(QtCore.Qt.AlignCenter) font = QtGui.QFont() font.setPointSize(20) self.movieImageLabel.setFont(font) self.movieImageLabel.setText(shortenedFileName) self.pushButton_2.setEnabled(True) self.video = fileName def getShortenedFilename(self, filename): temp = "" i = len(filename) - 1 while i > 0: if (filename[i] == '/' or filename[i] == '\\'): return temp temp = filename[i] + temp i -= 1 return temp def setupUi(self, selectVideo): selectVideo.setObjectName("selectVideo") selectVideo.resize(508, 584) self.label = QtWidgets.QLabel(selectVideo) self.label.setGeometry(QtCore.QRect(90, 40, 331, 61)) font = QtGui.QFont() font.setPointSize(24) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.pushButton = QtWidgets.QPushButton(selectVideo) self.pushButton.setGeometry(QtCore.QRect(140, 160, 201, 41)) self.pushButton.setObjectName("pushButton") self.pushButton.clicked.connect(self.getVideo) self.pushButton_2 = QtWidgets.QPushButton(selectVideo) self.pushButton_2.setGeometry(QtCore.QRect(140, 490, 201, 41)) self.pushButton_2.setCheckable(False) self.pushButton_2.setObjectName("pushButton_2") self.pushButton_2.clicked.connect(self.openFtoAWindow) self.pushButton_2.setEnabled(False) self.movieImageLabel = QtWidgets.QLabel(selectVideo) self.movieImageLabel.setGeometry(QtCore.QRect(160, 240, 211, 201)) self.movieImageLabel.setText("") self.movieImageLabel.setPixmap(QtGui.QPixmap("../camera.jpg")) self.movieImageLabel.setObjectName("movieImageLabel") self.video = QVideoWidget() self.video.resize(300, 300) self.video.move(0, 0) self.player = QMediaPlayer() self.player.setVideoOutput(self.video) self.retranslateUi(selectVideo) QtCore.QMetaObject.connectSlotsByName(selectVideo) self.widget = selectVideo def retranslateUi(self, selectVideo): _translate = QtCore.QCoreApplication.translate selectVideo.setWindowTitle(_translate("selectVideo", "Form")) self.label.setText(_translate("selectVideo", "Select a video")) self.pushButton.setText(_translate("selectVideo", "Select")) self.pushButton_2.setText(_translate("selectVideo", "Continue"))
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.setAttribute(Qt.WA_QuitOnClose, False) self.tIcon = QIcon( os.path.join(os.path.dirname(sys.argv[0]), "radio_bg.png")) self.setWindowIcon(self.tIcon) self.setGeometry(0, 0, 700, 400) self.setContentsMargins(6, 6, 6, 6) self.setStyleSheet(myStyleSheet(self)) self.setWindowTitle("Radio Suche") self.genreList = genres.splitlines() self.findfield = QLineEdit() self.findfield.setFixedWidth(250) self.findfield.addAction(QIcon.fromTheme("edit-find"), 0) self.findfield.setPlaceholderText("Suchbegriff eingeben und RETURN ") self.findfield.returnPressed.connect(self.findStations) self.findfield.setClearButtonEnabled(True) self.field = QPlainTextEdit() self.field.setContextMenuPolicy(Qt.CustomContextMenu) self.field.customContextMenuRequested.connect( self.contextMenuRequested) self.field.cursorPositionChanged.connect(self.selectLine) self.field.setWordWrapMode(QTextOption.NoWrap) ### genre box self.combo = QComboBox() self.combo.currentIndexChanged.connect(self.comboSearch) self.combo.addItem("wähle Genre") for m in self.genreList: self.combo.addItem(m) self.combo.setFixedWidth(150) ### toolbar ### self.tb = self.addToolBar("tools") self.tb.setContextMenuPolicy(Qt.PreventContextMenu) self.tb.setMovable(False) self.setCentralWidget(self.field) self.tb.addWidget(self.findfield) self.tb.addSeparator() self.tb.addWidget(self.combo) ### player ### self.player = QMediaPlayer() self.player.metaDataChanged.connect(self.metaDataChanged) self.startButton = QPushButton("Wiedergabe") self.startButton.setIcon(QIcon.fromTheme("media-playback-start")) self.startButton.clicked.connect(self.getURLtoPlay) self.stopButton = QPushButton("Stop") self.stopButton.setIcon(QIcon.fromTheme("media-playback-stop")) self.stopButton.clicked.connect(self.stopPlayer) self.statusBar().addPermanentWidget(self.startButton) self.statusBar().addPermanentWidget(self.stopButton) ## actions self.addToRadiolistAction = QAction( QIcon.fromTheme("add"), "zu myRadio Senderliste hinzufügen", self, triggered=self.addToRadiolist) self.getNameAction = QAction(QIcon.fromTheme("edit-copy"), "Sendername kopieren", self, triggered=self.getName) self.getUrlAction = QAction(QIcon.fromTheme("edit-copy"), "Sender-URL kopieren", self, triggered=self.getURL) self.getNameAndUrlAction = QAction(QIcon.fromTheme("edit-copy"), "Name,URL kopieren", self, triggered=self.getNameAndUrl) self.getURLtoPlayAction = QAction( QIcon.fromTheme("media-playback-start"), "Sender spielen", self, shortcut="F6", triggered=self.getURLtoPlay) self.addAction(self.getURLtoPlayAction) self.stopPlayerAction = QAction(QIcon.fromTheme("media-playback-stop"), "Wiedergabe stoppen", self, shortcut="F7", triggered=self.stopPlayer) self.addAction(self.stopPlayerAction) self.helpAction = QAction(QIcon.fromTheme("help-info"), "Hilfe", self, shortcut="F1", triggered=self.showHelp) self.addAction(self.helpAction) self.statusBar().showMessage("Welcome", 0) self.modified = False def closeEvent(self, event): self.stopPlayer() if self.modified == True: self.statusBar().showMessage("saved!", 0) self.msgbox( "neue Sender sind nach einem Neustart von myRadio verfügbar") def addToRadiolist(self): text = "" filename = os.path.join(os.path.dirname(sys.argv[0]), "myradio.txt") print(filename) with open(filename, 'r') as f: text = f.read() text = text[:text.rfind('\n')] f.close() textlist = text.splitlines() mycat = [] for line in textlist: if line.startswith("--"): mycat.append(line.replace("-- ", "").replace(" --", "")) ind = 1 for x in range(len(mycat)): if mycat[x] == self.combo.currentText(): ind = x break dlg = QInputDialog() mc, _ = dlg.getItem(self, "", "wähle Genre für den Sender", mycat, ind) entry = self.getNameAndUrl() print(mc, entry) filename = os.path.dirname(sys.argv[0]) + os.sep + "myradio.txt" print(filename) with open(filename, 'r') as f: text = f.read() text = text[:text.rfind('\n')] f.close() textlist = text.splitlines() if mc in mycat: for x in range(len(textlist)): if textlist[x] == f"-- {mc} --": textlist.insert(x + 1, entry) else: textlist.append(f"-- {mc} --") textlist.append(entry) with open(filename, 'w') as f: for x in reversed(range(len(textlist))): if textlist[x] == "\n": print(x) del textlist[x] text = '\n'.join(textlist) f.write(text) f.write('\n\n') f.close() self.modified = True def msgbox(self, message): msg = QMessageBox(1, "Information", message, QMessageBox.Ok) msg.exec() def comboSearch(self): if self.combo.currentIndex() > 0: self.findfield.setText(self.combo.currentText()) self.findStations() def getName(self): t = self.field.textCursor().selectedText().partition(",")[0] clip = QApplication.clipboard() clip.setText(t) def getURL(self): t = self.field.textCursor().selectedText().partition(",")[2] clip = QApplication.clipboard() clip.setText(t) def getNameAndUrl(self): t = self.field.textCursor().selectedText() clip = QApplication.clipboard() clip.setText(t) return (t) def selectLine(self): tc = self.field.textCursor() tc.select(QTextCursor.LineUnderCursor) tc.movePosition(QTextCursor.StartOfLine, QTextCursor.MoveAnchor) ##, tc.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) self.field.setTextCursor(tc) def showHelp(self): QMessageBox.information( self, "Information", "F6 -> Sender spielen\nF7 -> Wiedergabe stoppen") def stopPlayer(self): self.player.stop() self.statusBar().showMessage("Wiedergabe gestoppt", 0) ### QPlainTextEdit contextMenu def contextMenuRequested(self, point): cmenu = QMenu() if not self.field.toPlainText() == "": cmenu.addAction(self.getNameAction) cmenu.addAction(self.getUrlAction) cmenu.addAction(self.getNameAndUrlAction) cmenu.addSeparator() cmenu.addAction(self.addToRadiolistAction) cmenu.addSeparator() cmenu.addAction(self.getURLtoPlayAction) cmenu.addAction(self.stopPlayerAction) cmenu.addSeparator() cmenu.addAction(self.helpAction) cmenu.exec_(self.field.mapToGlobal(point)) def getURLtoPlay(self): url = "" tc = self.field.textCursor() rtext = tc.selectedText().partition(",")[2] stext = tc.selectedText().partition(",")[0] if rtext.endswith(".pls"): url = self.getURLfromPLS(rtext) elif rtext.endswith(".m3u"): url = self.getURLfromM3U(rtext) else: url = rtext print("stream url=", url) self.player.setMedia(QMediaContent(QUrl(url))) self.player.play() self.statusBar().showMessage("%s %s" % ("spiele", stext), 0) def metaDataChanged(self): if self.player.isMetaDataAvailable(): trackInfo = (self.player.metaData("Title")) trackInfo2 = (self.player.metaData("Comment")) if not trackInfo == None: self.statusBar().showMessage(trackInfo, 0) if not trackInfo2 == None: self.statusBar().showMessage("%s %s" % (trackInfo, trackInfo2)) def getURLfromPLS(self, inURL): print("detecting", inURL) t = "" if "&" in inURL: inURL = inURL.partition("&")[0] response = requests.get(inURL) print(response.text) if "http" in response.text: html = response.text.splitlines() if len(html) > 3: if "http" in str(html[1]): t = str(html[1]) elif "http" in str(html[2]): t = str(html[2]) elif "http" in str(html[3]): t = str(html[3]) elif len(html) > 2: if "http" in str(html[1]): t = str(html[1]) elif "http" in str(html[2]): t = str(html[2]) else: t = str(html[0]) url = t.partition("=")[2].partition("'")[0] return (url) else: print("Liste schlecht formatiert") def getURLfromM3U(self, inURL): print("detecting", inURL) response = requests.get(inURL) html = response.text.splitlines() print(html) if "#EXTINF" in str(html): url = str(html[1]).partition("http://")[2].partition('"')[0] url = f"http://{url}" else: if len(html) > 1: url = str(html[1]) else: url = str(html[0]) print(url) return (url) def findStations(self): self.field.setPlainText("") mysearch = self.findfield.text() self.statusBar().showMessage("searching ...") rb = RadioBrowser() myparams = {'name': 'search', 'nameExact': 'false'} for key in myparams.keys(): if key == "name": myparams[key] = mysearch r = rb.station_search(params=myparams) n = "" m = "" for i in range(len(r)): for key, value in r[i].items(): if str(key) == "name": n = value.replace(",", " ") if str(key) == "url": m = value self.field.appendPlainText("%s,%s" % (n, m)) if not self.field.toPlainText() == "": self.statusBar().showMessage(str(self.field.toPlainText().count('\n')+1) \ + " '" + self.findfield.text() + "' Stationen gefunden") else: self.statusBar().showMessage("nothing found", 0)
def __init__(self, parent=None): super(Video, self).__init__(parent) self.setWindowTitle("Video Editor") self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) videoWidget = QVideoWidget() self.playButton = QPushButton() self.playButton.setEnabled(False) self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playButton.clicked.connect(self.play) self.positionSlider = QSlider(Qt.Horizontal) self.positionSlider.setRange(0, 0) self.positionSlider.sliderMoved.connect(self.setPosition) self.errorLabel = QLabel() self.errorLabel.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) # Upload video openAction = QAction(QIcon('open.png'), '&Open', self) openAction.setShortcut('Ctrl+O') openAction.setStatusTip('Open movie') openAction.triggered.connect(self.openFile) # Exit video exitAction = QAction(QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.exitCall) # Menu bar and add action menuBar = self.menuBar() fileMenu = menuBar.addMenu('&File') fileMenu.addAction(openAction) fileMenu.addAction(exitAction) # Window content wid = QWidget(self) self.setCentralWidget(wid) # Layouts for widget controlLayout = QHBoxLayout() controlLayout.setContentsMargins(0, 0, 0, 0) controlLayout.addWidget(self.playButton) controlLayout.addWidget(self.positionSlider) layout = QVBoxLayout() layout.addWidget(videoWidget) layout.addLayout(controlLayout) layout.addWidget(self.errorLabel) wid.setLayout(layout) self.mediaPlayer.setVideoOutput(videoWidget) self.mediaPlayer.stateChanged.connect(self.mediaStateChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.durationChanged.connect(self.durationChanged) self.mediaPlayer.error.connect(self.handleError)
class VideoWindow(QVideoWidget): def __init__(self, filename): super().__init__() if not path.exists(filename): print("\nFile '{}' doesn't exist!".format(filename)) quit() self.width = SCREEN_WIDTH self.filename = filename self.video = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.video.setVideoOutput(self) #setting the video output self.video.mediaStatusChanged.connect( self.end_of_video) #setting a signal of the video end self.video.setMedia(QMediaContent( QUrl.fromLocalFile(filename))) #openning the file self.video.play() self.video.pause() def start(self): info_message( QMessageBox.Information, 'Instruction', 'In this part of the experiment, you will need to watch a video from the beginning till the end.\n\nNote: If you want to exit the experiment before the end, click the "Exit the experiment" buttom at the bottom of the screen.' ) self.video.play() def exit_confirmation(self): #asking confirmation to stop the video self.video.pause() returnValue = exit_question_message() if returnValue == QMessageBox.Yes: info_message(QMessageBox.Information, 'Experiment termination', 'The experiment has been stopped by the user') quit() else: self.video.play() def end_of_video(self, status): #responding to the end signal if status == self.video.EndOfMedia: info_message(QMessageBox.Information, 'The end of the video', 'The video has finished') if self.filename == FILENAME1: a = self.ask_A() if a != '3': info_message( QMessageBox.Information, 'The end of the experiment', 'This is the end of the experiment.\nThank you for your participation.' ) quit() experiment.next_in_scenario() def ask_A(self): '''ask how many A''' while True: #Doesn't allow to close the window items = ('0', '1', '2', '3', '4', '5') item, okPressed = QInputDialog().getItem( self, 'Question', 'How many letters A have you seen?\nThe number of A:', items, 0, False) if okPressed and item: return item
def initMainWindow(self): """ This function initialize all the buttons and all the setting for displaying and control the video. """ self.setWindowIcon( QtGui.QIcon( "../resources/icons/GUI_Icons/1519132568_movavi-video-editor.png" )) #delete all temp files self.deleteAllTemp() self.setWindowTitle("VideoEditor") """<Objects>""" #Object for controling all edit functions self.edit = Panel() """</Objects>""" """--------------------<Global variables>----------------------------""" #Thread manager variable self.threadmanager = True #Audio file holder self.audioFile = '' #frame time variable self.frameTime = '' #frame file path self.frameFilePath = '' #Total number of curent media opened self.totalIndex = -1 #Dictionary for index and path for the media self.curentFiles = {} #Index that indicates the curent media selected self.curentIndex = self.totalIndex #Curent index of Concatenate ListView self.curentIndexOfConcatenateList = -1 #Dictionary with all video path for concatenate self.concatenateVideos = {} #Total number of videos added to the concatenate list view self.totalNrOfVideosConcat = -1 #Media play speed self.speed = 1 # self.subtitlesFileVG = '' """-------------------</Global variables>----------------------------""" """----------------<Media player settings>---------------------------""" #Create a mediaplayer object to control the video self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.mediaPlayer.setVolume(50) #Create a playlist object for multiple videos self.playlist = QMediaPlaylist() self.mediaPlayer.setPlaylist(self.playlist) self.model = PlaylistModel(self.playlist) self.videoFiles.setModel(self.model) self.playlist.currentIndexChanged.connect( self.playlist_position_changed) selection_model = self.videoFiles.selectionModel() selection_model.selectionChanged.connect( self.playlist_selection_changed) #Create videoWidget object for displaying the video videoWidget = QVideoWidget() #videoWidget set self.videoPreviewLayout = QVBoxLayout() self.videoPreviewLayout.addWidget(videoWidget) self.vpfVideoPreview.setLayout(self.videoPreviewLayout) """----------------</Media player settings>--------------------------""" """-----------------<Buttons&Labels settings>-------------------------""" #Create Open Video button in taskbar self.open = QAction('&Open Video', self) self.open.setStatusTip('Open Video') self.menuFiles.addAction(self.open) self.setAcceptDrops(True) #PlayButton self.playButton.setEnabled(False) #Speed label self.speedLabel.setText("1.0x") #Slider settings timeline self.videoTimeSlider.setRange(0, 0) #Slider settings volume self.volume.setRange(0, 100) self.volume.setValue(50) self.volumeTextDisplay.setText("50%") #Cut lock buttons self.lockButtonStart.setCheckable(True) self.lockButtonFinish.setCheckable(True) #Cut text editor settings self.cutStart.setReadOnly(True) self.cutFinish.setReadOnly(True) self.cutStart.setText("0:00:00") self.cutFinish.setText("0:00:00") #Resolution Image settings self.resolutionIcon.setPixmap( QPixmap("../resources/icons/GUI_Icons/720.png")) """-----------------</Buttons&Labels settings>-------------------------""" """-----------------<Buttons connections>------------------------------""" """ -----------<Player buttons>--------- """ #Play button self.playButton.clicked.connect(self.playVideo) #back 15 seconds Button self.skipbackButton.clicked.connect(self.skipbackFunction) #skip 15 seconds forward Button self.skipforwardButton.clicked.connect(self.skipforwadFunction) #fastorForward button self.fastForward.clicked.connect(self.fastForwardFunction) #rewind button self.rewind.clicked.connect(self.rewindFunction) #Add video button self.addButton.clicked.connect(self.openFile) #Remove video button self.deleteButton.clicked.connect(self.RemoveVideo) #save video self.saveVideo.clicked.connect(self.saveVideoFunction) #Time slider self.videoTimeSlider.sliderMoved.connect(self.setPosition) #Volume slider self.volume.sliderMoved.connect(self.volumeControl) #media player change state self.mediaPlayer.stateChanged.connect(self.mediaStateChange) self.mediaPlayer.positionChanged.connect(self.positionChange) self.mediaPlayer.durationChanged.connect(self.durationChange) """ -----------</Player buttons>--------- """ #Open file self.open.triggered.connect(self.openFile) """ -------------<Edit Buttons>----------------- """ """<Concatenate>""" #Create a model for Concatenate Lisview self.concatenateModel = QtGui.QStandardItemModel() #Set the model to the Concatenate List view self.concatenateList.setModel(self.concatenateModel) #Concatenate list of videos self.concatenateList.clicked[QtCore.QModelIndex].connect( self.setConcatenateIndex) #Add button to concatenate list self.addConcatenate.clicked.connect(self.addVideoToConcatenate) # When you receive the signal, you call QtGui.QStandardItemModel.itemFromIndex() # on the given model index to get a pointer to the item self.removeConcatenate.clicked.connect(self.removeVideoToConcatenate) #Concatenate Button self.concatenateButton.clicked.connect(self.concatenateThreadFunction) """</Concatenate>""" """<Cut>""" #Lock cut filed1 self.lockButtonStart.clicked.connect(self.lockButtonChangeIconStart) #Lock cut filed2 self.lockButtonFinish.clicked.connect(self.lockButtonChangeIconFinish) #Cut button self.cutButton.clicked.connect(self.cutThreadFunction) """</Cut>""" """<Resolution>""" #Resoluiton ComboBox for selecting the desired resolution self.ResolutionsList.currentIndexChanged.connect( self.changeResolutionDisplay) #Change resolution button self.changeResolution.clicked.connect(self.changeResolutionThread) """</Resoluton>""" """<Mirror>""" #Mirror button self.mirroringButton.clicked.connect(self.mirrorThread) """</Mirror>""" """<Audio replace>""" self.openAudioFile.clicked.connect(self.openAudio) self.removeAudioFile.clicked.connect(self.removeAudioFileFunction) self.audioModeSelect.currentIndexChanged.connect( self.changeAudioBackground) self.AddAudio.clicked.connect(self.SoundReplaceThread) """</Audio replace>""" """<GetFrame>""" self.getFrameButton.clicked.connect(self.GetFrameFunction) #self.saveFrameButton.setShortcut("Ctrl+S") self.saveFrameButton.setStatusTip('Save File') self.saveFrameButton.clicked.connect(self.saveFrame) """"</GetFrame>""" """<AddSubtitles>""" self.loadSubtitles.clicked.connect(self.loadSubtitlesFunction) self.cleanButton.clicked.connect(self.removeSubtitlesFunction) self.addSubtitle.clicked.connect(self.addSubtitlesThread) """</AddSubtitles>""" """<VideoGrep>""" self.loadSubtitlesVG.clicked.connect(self.loadSubtitlesVideoGrep) self.cleanButtonVideoGrep.clicked.connect( self.removeSubtitlesVideoGrep) self.videoGrep.clicked.connect(self.videoGrepThread) """</VideoGrep>""" """ -------------</Edit Buttons>----------------- """ """ -------------<Shortcut Buttons>--------------- """ self.soundShortcut.clicked.connect(self.soundShortcutKey) self.getFrameShortcut.clicked.connect(self.getFrameShortcutKey) self.cutShortcut.clicked.connect(self.cutShortcutKey) self.concatShortcut.clicked.connect(self.concatShortcutKey) self.mirrorShortcut.clicked.connect(self.mirrorShortcutKey) """ -------------</Shortcut Buttons>--------------- """ """-----------------</Buttons connections>----------------------------""" """-------------------<Threads for editing>--------------------------""" self.pool = QThreadPool() """-------------------</Threads for editing>--------------------------""" """<Experimental>""" qtimeline = QTimeLine(360, 1) self.test = QVBoxLayout() qtimeline2 = QTimeLine(360, 1) self.test.addWidget(qtimeline) self.test.addWidget(qtimeline2) self.sfTimeLineFrame.setLayout(self.test) #self.editMenu.setCurrentIndex(5) """</Experimental>""" #Set output to the video self.mediaPlayer.setVideoOutput(videoWidget)
class App(QMainWindow): def __init__(self): super().__init__() self.player = QMediaPlayer() self.playlist = QMediaPlaylist() self.playlist.setPlaybackMode(QMediaPlaylist.Sequential) self.title = 'JPR Reader GUI version2' self.left = 50 self.top = 100 self.width = 1200 self.height = 800 self.fileReady = False self.tableRow = 5 self.tableCol = 15 self.row = 2 self.audiolist = [] self.configFile = ".//configurationFile.xlsx" self.dict = { 'num': None, 'partner': None, 'parcel': None, 'exception': None, 'box': None } self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # menu menubar = self.menuBar() filemenu = menubar.addMenu('File') fileAct = QAction('Open File', self) fileAct.setShortcut('Ctrl+O') filemenu.addAction(fileAct) fileAct.triggered.connect(self.openFileNameDialog) # status_bar self.statusbar = self.statusBar() # tabs self.tabs = QTabWidget() self.tab1 = QWidget(self) self.tab2 = QWidget(self) self.tabs.addTab(self.tab1, "조작") self.tabs.addTab(self.tab2, "설정") self.setCentralWidget(self.tabs) # tab1 gui self.ButtonGroupBox = self.createButtonGroupBox() self.createLogTable() self.tab1.layout = QVBoxLayout() self.tab1.layout.addWidget(self.ButtonGroupBox) self.tab1.layout.addWidget(self.logTable) self.tab1.setLayout(self.tab1.layout) # tab2 gui self.explanation = QLabel() self.explanation.setText("""<<< JPR reader 설정 테이블 >>> 이곳에서 JPR reader가 읽어주는 항목과 아이템을 설정할 수 있습니다. 항목과 아이템의 설정 방법은 셀을 더블 클릭한 후 이름을 입력하는 방식으로진행됩니다. 그 후 떠오른 파일 탐색기에서 지정할 mp3파일을 선택해 주세요. 설정의 확인은 셀의 색으로 확인 가능합니다. 지정이 완료된 항목은 노란색, 아이템은 하늘색으로 표시됩니다. 지정이 되지 않은 셀은 빨간색으로 표시됩니다. 행과 열 버튼으로 테이블의 크기를 조절할 수 있으며 초기화시 모든 설정은 사라지며 테이블은 5by5로 초기화 됩니다. <<<주의사항>>> 1. 첫번째 열은 반드시 항목을 입력해 주세요. 2. 입력되는 이름은 엑셀파일에서 표현된 명칭과 완벽히 일치해야 합니다.(엔터나 스페이스, 오타 주의!) 3. 초기화를 누르면 처음부터 모든 항목과 아이템을 지정해야 합니다. 4. 엑셀 파일의 ()나 /을 통해 구분한 아이템은 따로 입력해 주세요. 5. 사용하는 엑셀파일의 구조를 유지해 주세요. 변경시 프로그램의 수정이 필요할 수 있습니다.(예: '박스'항목은 항상 있을 것으로 간주됩니다.) 제작자 정보: 김현우([email protected])""") self.explanation.setAlignment(Qt.AlignCenter) self.createConfigTable() self.createHorizontalButtons2() self.tab2.layout = QVBoxLayout() self.tab2.layout.addWidget(self.explanation) self.tab2.layout.addWidget(self.configTable) self.tab2.layout.addWidget(self.horizontalButtons2) self.tab2.setLayout(self.tab2.layout) # Show widget self.show() def openFileNameDialog(self): fileName, _ = QFileDialog.getOpenFileName(self, "Open file", "", "All Files (*)") if not fileName: self.statusbar.showMessage('Fail to load file...') else: self.wb = load_workbook(fileName.strip()) self.ws = self.wb.active self.fileReady = True self.row = 2 self.statusbar.showMessage('succeed to load file...') self.logTable.clear() # set logTable's horizontal header self.logTable.setHorizontalHeaderItem(0, QTableWidgetItem("포장순번")) self.logTable.setHorizontalHeaderItem(1, QTableWidgetItem("거래처명")) self.logTable.setHorizontalHeaderItem(2, QTableWidgetItem("배송센터")) self.logTable.setHorizontalHeaderItem(3, QTableWidgetItem("특이사항")) self.logTable.setHorizontalHeaderItem(4, QTableWidgetItem("박스")) # initialize dictionary self.dict = { 'num': None, 'partner': None, 'parcel': None, 'exception': None, 'box': None } col = 6 num = 0 header = str(self.ws.cell(row=1, column=col + 1).value).strip() while header != 'None': self.dict[header] = None col = col + 1 num = num + 1 header = str(self.ws.cell(row=1, column=col + 1).value).strip() self.tableCol = 5 + num self.logTable.setColumnCount(self.tableCol) for c in range(5, self.tableCol): self.logTable.setHorizontalHeaderItem( c, QTableWidgetItem(list(self.dict.keys())[c])) def createButtonGroupBox(self): buttonGroupBox = QGroupBox("Controller") vLayout = QVBoxLayout() pre_button = QPushButton('w', self) pre_button.clicked.connect(self.pre_click) pre_button.setIcon(QIcon('.\\img\\up-arrow.png')) pre_button.setIconSize(QSize(600, 100)) pre_button.setShortcut('w') vLayout.addWidget(pre_button) hBottensWidget = self.createHButtons() vLayout.addWidget(hBottensWidget) next_button = QPushButton('x', self) next_button.clicked.connect(self.next_click) next_button.setIcon(QIcon('.\\img\\down-arrow.png')) next_button.setIconSize(QSize(600, 100)) next_button.setShortcut('x') vLayout.addWidget(next_button) buttonGroupBox.setLayout(vLayout) return buttonGroupBox def createHButtons(self): hBottensWidget = QWidget() hLayout = QHBoxLayout() back_button = QPushButton('a', self) back_button.clicked.connect(self.back_click) back_button.setIcon(QIcon('.\\img\\left-arrow.png')) back_button.setIconSize(QSize(200, 150)) back_button.setShortcut('a') hLayout.addWidget(back_button) cur_button = QPushButton('s', self) cur_button.clicked.connect(self.cur_click) cur_button.setIcon(QIcon('.\\img\\reload.png')) cur_button.setIconSize(QSize(200, 150)) cur_button.setShortcut('s') hLayout.addWidget(cur_button) forward_button = QPushButton('d', self) forward_button.clicked.connect(self.forward_click) forward_button.setIcon(QIcon('.\\img\\right-arrow.png')) forward_button.setIconSize(QSize(200, 150)) forward_button.setShortcut('d') hLayout.addWidget(forward_button) hBottensWidget.setLayout(hLayout) return hBottensWidget def createHorizontalButtons2(self): self.horizontalButtons2 = QGroupBox("설정 변경") layout = QHBoxLayout() plusRowButton = QPushButton('행+', self) plusRowButton.clicked.connect(self.plus_row) layout.addWidget(plusRowButton) plusColButton = QPushButton('열+', self) plusColButton.clicked.connect(self.plus_col) layout.addWidget(plusColButton) init_button = QPushButton('초기화', self) init_button.clicked.connect(self.initialize) layout.addWidget(init_button) self.horizontalButtons2.setLayout(layout) def createLogTable(self): # Create table self.logTable = QTableWidget() self.logTable.setRowCount(self.tableRow) self.logTable.setColumnCount(self.tableCol) self.logTable.move(0, 0) def createConfigTable(self): self.configTable = QTableWidget() try: # load configurationFile cwb = load_workbook(self.configFile.strip()) except: # message box string = "설정파일을 불러올 수 없습니다." QMessageBox.question(self, 'Error', string, QMessageBox.Ok, QMessageBox.Ok) else: # Get matadata cws = cwb.active self.crow = cws.cell(row=1, column=1).value self.ccol = cws.cell(row=1, column=2).value # Configure table self.configTable.setRowCount(self.crow) self.configTable.setColumnCount(self.ccol) self.configTable.move(0, 0) # Load data from configFile for i in range(self.crow): for j in range(self.ccol): item = str(cws.cell(row=i + 2, column=j + 1).value).strip() if item == 'None': item = '' self.configTable.setItem(i, j, QTableWidgetItem(item)) # check if files exist arr = listdir('./audio_clips') for row in range(self.crow): for col in range(self.ccol): # if 박스(0,0) if row == 0 and col == 0: continue # reset backgound color self.configTable.item(row, col).setBackground(QColor(255, 0, 0)) # if file exist, change background color fname = str(row) + '_' + str(col) + '.mp3' if fname in arr: if row == 0: self.configTable.item(row, col).setBackground( QColor(255, 255, 0)) else: self.configTable.item(row, col).setBackground( QColor(0, 255, 255)) # 박스(0,0) self.configTable.setItem(0, 0, QTableWidgetItem('박스')) self.configTable.item(0, 0).setBackground(QColor(255, 255, 255)) # link the callback function self.configTable.itemDoubleClicked.connect(self.item_doubleClicked) self.configTable.itemChanged.connect(self.item_changed) def setLogTable(self): # shifting other rows for r in range(1, self.tableRow): for c in range(self.tableCol): try: self.logTable.item(r, c).setBackground(QColor(255, 255, 255)) self.logTable.setItem(r - 1, c, self.logTable.item(r, c).clone()) except: pass # set current row for idx, key in enumerate(list(self.dict.keys())): if type(self.dict[key]) is list: self.logTable.setItem( self.tableRow - 1, idx, QTableWidgetItem(' '.join(self.dict[key]))) self.logTable.item(self.tableRow - 1, idx).setBackground(QColor(255, 255, 0)) else: self.logTable.setItem(self.tableRow - 1, idx, QTableWidgetItem(self.dict[key])) self.logTable.item(self.tableRow - 1, idx).setBackground(QColor(255, 255, 0)) def read(self): # 포장 순번 self.dict['num'] = str(self.ws.cell(row=self.row, column=3).value[2:]).strip() # 거래처명 self.dict['partner'] = str(self.ws.cell(row=self.row, column=5).value).strip() # 배송센터 self.dict['parcel'] = str(self.ws.cell(row=self.row, column=4).value).strip() # 특이사항 self.dict['exception'] = str( self.ws.cell(row=self.row, column=6).value).strip() # 박스 self.dict['box'] = str(self.ws.cell(row=self.row, column=2).value).strip() # left things print(len(self.dict)) for i in range(5, len(self.dict)): header = str(self.ws.cell(row=1, column=i + 2).value).strip() self.dict[header] = str( self.ws.cell(row=self.row, column=i + 2).value).strip() self.parsing(header, self.dict[header]) print(self.dict) self.setLogTable() def parsing(self, key, val): if val == 'None' or val == '': self.dict[key] = None else: if '(' in val or '/' in val: arr = re.split('[(/]', val) for i in range(len(arr)): if ')' in arr[i]: arr[i] = arr[i][:arr[i].index(')')] arr[i] = arr[i].strip() self.dict[key] = arr else: self.dict[key] = val def itemFromKeyVal(self, key, val): items = self.configTable.findItems(val, Qt.MatchExactly) if len(items) <= 0: # Error string = '(' + key + ', ' + val + ') ' + '아이템을 찾을 수 없습니다.' QMessageBox.question(self, 'Error', string, QMessageBox.Ok, QMessageBox.Ok) else: for item in items: if self.configTable.item(0, item.column()).data(0) == key: return item def load_audiolist(self): for key, val in self.dict.items(): # 포장순번 if key == 'num': for i in range(len(self.dict['num'])): self.audiolist.append('_' + val[i]) # beep self.audiolist.append('_beep') # 택배발송 elif key == 'parcel': if val == '택배발송': self.audiolist.append('_택배발송') # beep self.audiolist.append('_beep') # 박스 elif key == 'box': item = self.itemFromKeyVal('박스', val) if item: self.audiolist.append( str(item.row()) + '_' + str(item.column())) # beep self.audiolist.append('_beep') elif key in ['partner', 'exception']: pass # general case else: # The case(val == None) will be ignored if val == None: pass # when val is list elif type(val) == list: for idx, eachVal in enumerate(val): item = self.itemFromKeyVal(key, eachVal) if item: if idx == 0: self.audiolist.append( '0_' + str(item.column())) # key self.audiolist.append( str(item.row()) + '_' + str(item.column())) # val # beep self.audiolist.append('_beep') # when val is not list else: item = self.itemFromKeyVal(key, val) if item: if val == '1' or key == val: self.audiolist.append('0_' + str(item.column())) # key else: self.audiolist.append('0_' + str(item.column())) # key self.audiolist.append( str(item.row()) + '_' + str(item.column())) # val # beep self.audiolist.append('_beep') print(self.audiolist) def speak(self): self.playlist.clear() for clip in self.audiolist: url = QUrl.fromLocalFile('./audio_clips/' + clip + '.mp3') #print(url) self.playlist.addMedia(QMediaContent(url)) self.player.setPlaylist(self.playlist) self.player.play() #----------------------- Control button callback -----------------------# @pyqtSlot() def pre_click(self): if not self.fileReady: self.cur_click() else: if self.row == 2: self.statusbar.showMessage("Can't be previous.") else: self.row -= 1 self.dict = self.dict.fromkeys(self.dict, None) del self.audiolist[:] self.read() self.load_audiolist() self.speak() @pyqtSlot() def cur_click(self): if not self.fileReady: string = '파일이 준비되어 있지 않습니다.' QMessageBox.question(self, '경고', string, QMessageBox.Ok, QMessageBox.Ok) self.openFileNameDialog() else: self.dict = self.dict.fromkeys(self.dict, None) del self.audiolist[:] self.read() self.load_audiolist() self.speak() @pyqtSlot() def next_click(self): if not self.fileReady: self.cur_click() else: if self.row == self.ws.max_row: self.statusbar.showMessage("It's over.") else: self.row += 1 self.dict = self.dict.fromkeys(self.dict, None) del self.audiolist[:] self.read() self.load_audiolist() self.speak() @pyqtSlot() def back_click(self): if self.playlist.mediaCount() == 0: self.cur_click() elif self.playlist.mediaCount() != 0: p = re.compile('.+_beep.+') cnt = 0 for i in range(self.playlist.mediaCount()): # if it's start point, start at here if self.playlist.currentIndex() == 0: break # go backward self.playlist.setCurrentIndex(self.playlist.previousIndex(1)) # start at previous beep point if p.match(str(self.playlist.currentMedia().canonicalUrl())): cnt = cnt + 1 if cnt == 2: print(self.playlist.currentIndex()) if self.player.state() == QMediaPlayer.StoppedState: self.player.play() break @pyqtSlot() def forward_click(self): if self.playlist.mediaCount() == 0: self.cur_click() elif self.playlist.mediaCount() != 0: p = re.compile('.+_beep.+') for i in range(self.playlist.mediaCount()): # don't go further from end point if self.playlist.currentIndex() < 0: break # go forward self.playlist.setCurrentIndex(self.playlist.nextIndex(1)) # start at next beep point if p.match(str(self.playlist.currentMedia().canonicalUrl())): print(self.playlist.currentIndex()) break #----------------------- Configuration button callback -----------------------# @pyqtSlot() def plus_row(self): # change configTable self.crow = self.crow + 1 self.configTable.setRowCount(self.crow) # fill the generated cell self.configTable.itemChanged.disconnect(self.item_changed) for col in range(self.ccol): self.configTable.setItem(self.crow - 1, col, QTableWidgetItem('')) self.configTable.item(self.crow - 1, col).setBackground(QColor(255, 0, 0)) self.configTable.itemChanged.connect(self.item_changed) @pyqtSlot() def plus_col(self): # change configTable self.ccol = self.ccol + 1 self.configTable.setColumnCount(self.ccol) # fill the generated cell self.configTable.itemChanged.disconnect(self.item_changed) for row in range(self.crow): self.configTable.setItem(row, self.ccol - 1, QTableWidgetItem('')) self.configTable.item(row, self.ccol - 1).setBackground( QColor(255, 0, 0)) self.configTable.itemChanged.connect(self.item_changed) @pyqtSlot() def initialize(self): # remove configurable audio files arr = listdir('./audio_clips') p = re.compile('_.+') for file in arr: if p.match(file): continue remove('./audio_clips/' + file) # init configTable self.configTable.itemChanged.disconnect(self.item_changed) # lock self.configTable.clear() self.crow = 5 self.ccol = 5 self.configTable.setRowCount(self.crow) self.configTable.setColumnCount(self.ccol) # reset configTable item for row in range(self.crow): for col in range(self.ccol): self.configTable.setItem(row, col, QTableWidgetItem('')) self.configTable.item(row, col).setBackground(QColor(255, 0, 0)) self.configTable.setItem(0, 0, QTableWidgetItem('박스')) self.configTable.item(0, 0).setBackground(QColor(255, 255, 255)) self.configTable.itemChanged.connect(self.item_changed) # unlock # init configFile self.update_configFile() #---------------------- ConfigTable signal callback ------------------------# def item_doubleClicked(self, item): self.previousItem = item.data(0) print(self.previousItem) def update_configFile(self): cwb_w = Workbook(write_only=True) cws_w = cwb_w.create_sheet() cws_w.append([self.crow, self.ccol]) for row in range(self.crow): itemList = [] for col in range(self.ccol): itemList.append(self.configTable.item(row, col).data(0)) cws_w.append(itemList) try: cwb_w.save(self.configFile) except: string = """설정파일이 열려있을 수 있습니다. 설정파일을 닫은 후에 다시 시도하세요.""" QMessageBox.question(self, 'Error', string, QMessageBox.Ok, QMessageBox.Ok) def item_changed(self, item): self.configTable.itemChanged.disconnect(self.item_changed) # lock if item.row() == 0 and item.column() == 0: string = "이 항목은 바꿀 수 없습니다." QMessageBox.question(self, 'Error', string, QMessageBox.Ok, QMessageBox.Ok) self.configTable.setItem(item.row(), item.column(), QTableWidgetItem(self.previousItem)) else: # get file name fileName, _ = QFileDialog.getOpenFileName(self, "Open file", "", "All Files (*)") # count the number of key that has same name keys = self.configTable.findItems(item.data(0), Qt.MatchExactly) kcnt = 0 for key in keys: if key.row() == 0: kcnt = kcnt + 1 # count the number of atribute that has same name atributes = self.configTable.findItems(item.data(0), Qt.MatchExactly) acnt = 0 for atribute in atributes: if atribute.row() == 0: pass elif atribute.column() == item.column(): acnt = acnt + 1 # change is accepted only in case of uniqueness and existence and it is not 박스(0,0) if kcnt >= 2: string = "항목명이 같을 수 없습니다." QMessageBox.question(self, 'Error', string, QMessageBox.Ok, QMessageBox.Ok) self.configTable.setItem(item.row(), item.column(), QTableWidgetItem(self.previousItem)) elif acnt >= 2: string = "같은 항목에 같은 이름의 아이템을 둘 수 없습니다." QMessageBox.question(self, 'Error', string, QMessageBox.Ok, QMessageBox.Ok) self.configTable.setItem(item.row(), item.column(), QTableWidgetItem(self.previousItem)) elif fileName: # copy file to local dir dst = "./audio_clips./" + str(item.row()) + '_' + str( item.column()) + '.mp3' copyfile(fileName, dst) # change cell color if item.row() == 0: self.configTable.item(item.row(), item.column()).setBackground( QColor(255, 255, 0)) else: self.configTable.item(item.row(), item.column()).setBackground( QColor(0, 255, 255)) # update configFile self.update_configFile() else: string = "선택이 취소됨." QMessageBox.question(self, 'Error', string, QMessageBox.Ok, QMessageBox.Ok) self.configTable.setItem(item.row(), item.column(), QTableWidgetItem(self.previousItem)) self.configTable.itemChanged.connect(self.item_changed) # unlock
class FirstWindow(QWidget): """ В этом классе описывается внешний вид, логика и функционал моего видеоплеера версии 0.01 постораюсь по мере возможности улучшать свой проект добавляя функционал и удобства , это \'документация\', надеюсь моя программа тебе понравится P.S знаю что много плохого кода. сорри """ def __init__(self): """ Инициализируем Класс нашего главного окна и в нем прописывем основные характеристики нашего окна (размер , цвет , "тайтл" и вызывает методы в которых отслеживаются события(перемещение мыши) и прописан внешний вид интерфейса """ super().__init__() self.setWindowTitle('v_|0.0.1|') self.resize(1280, 666) self.setWindowIcon(QIcon(resource_path(r'ico\L.ico'))) self.setStyleSheet("background-color: #F0F0F0;") self.setMouseTracking(True) self.setCursor(Qt.PointingHandCursor) self.init_ui() self.init_handlers() self.setAcceptDrops(True) # self.setWindowFlag(Qt.FramelessWindowHint) def init_handlers(self): # обработка нажатия для октрытия 2 окна self.imageBtn.clicked.connect(self.show_window_2) def show_window_2(self): # открытие 2 окна self.second_window = WindowForImage() self.second_window.show() def event(self, e): """ Метод обработчик который фиксирует взаимодействия с клавиатурой и мышью для манипуляцией над процессом показа виде (изменения громкости , перемотка и остановка """ if e.type() == QEvent.MouseButtonDblClick: pass elif e.type() == QEvent.Wheel: pass elif e.type() == QEvent.KeyPress: if e.key() == Qt.Key_Space: self.play_video() if e.key() == Qt.Key_VolumeUp: self.plus_volume() if e.key() == Qt.Key_VolumeDown: self.min_volume() elif e.type() == QEvent.MouseButtonPress: if e.buttons() & Qt.LeftButton: self.play_video() return QWidget.event(self, e) def mouseMoveEvent(self, event): """ Здесь я пытался реализовать обработчик , который показался мне интересным , во время воспроизведения видео если курсор мыши находится внутри "видеовиджета" то ползунок громкости , продолжительности видео и кнопки громкости скроются """ if self.isMaximized(): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: slider_y = (self.slider.pos().y() - 3) if event.pos().y() > slider_y: self.blef_win_on() elif event.pos().y() < slider_y: self.blef_win() if self.mediaPlayer.state() == QMediaPlayer.PausedState: self.blef_win_on() else: self.blef_win_on() if self.hslider.isVisible(): self.blef_win_on() def init_ui(self): conf_for_blank = ''' QPushButton{ border: none; margin: 0px; padding: 0px; background-color:#F0F0F0; } ''' config = ''' QPushButton{ border: none; margin: 0px; padding: 0px; background-color:#F0F0F0; } QPushButton:hover{ background-color: #B4B4B4; border-radius:7px; width: 30px; } ''' global hboxLayout global hboxLayout2 global vboxLayout global videowidget global openBtn # создание экземпляра(объекта) класса QMediaPlayer() и передача аргуметов # QMediaPlayer.VideoSurface указывает что он 'служит' для воспроизведения видео self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) # создание экземпляра(объекта) класса QVideoWidget() videowidget = QVideoWidget() videowidget.setStyleSheet('background-color: #B4B4B4;') # создание button(кнопки открыть) openBtn = QPushButton() openBtn.setStyleSheet(config) openBtn.setIcon(QIcon(resource_path(r'ico\folders.png'))) openBtn.setIconSize(QSize(20, 20)) openBtn.clicked.connect(self.open_file) openBtn.setToolTip('Открытие папок для просмотра файлов') openBtn.setToolTipDuration(2500) # создание button (кнопки для запуска) self.playBtn = QPushButton() self.playBtn.setEnabled(False) self.playBtn.setFlat(True) self.playBtn.setStyleSheet(config) self.playBtn.setIcon(QIcon(resource_path(r'ico\play.png'))) self.playBtn.setIconSize(QSize(40, 40)) self.playBtn.clicked.connect(self.play_video) # self.playBtn.clicked.connect(self.play_video) # создание button(кнопки для перемотки вперед) self.forwardBtn = QPushButton() self.forwardBtn.setEnabled(False) self.forwardBtn.setIcon(QIcon(resource_path(r'ico\forward.png'))) self.forwardBtn.setStyleSheet(config) self.forwardBtn.setIconSize(QSize(20, 20)) self.forwardBtn.clicked.connect(self.go_forward) # создание button (для перемотки назад) self.backBtn = QPushButton() self.backBtn.setEnabled(False) self.backBtn.setIcon(QIcon(resource_path(r'ico\backward .png'))) self.backBtn.setStyleSheet(config) self.backBtn.setIconSize(QSize(20, 20)) self.backBtn.clicked.connect(self.go_back) # для volume(громкости) self.volumeBtn = QPushButton() self.volumeBtn.setObjectName('volume_btn') self.volumeBtn.setIcon(QIcon(resource_path(r'ico\volume1.png'))) self.volumeBtn.setStyleSheet(config) self.volumeBtn.setIconSize(QSize(17, 17)) self.volumeBtn.clicked.connect(self.volume) # настройка button(кнопок) self.screenBtn = QPushButton() self.screenBtn.setObjectName('fullscreen') self.screenBtn.setStyleSheet(config) self.screenBtn.setIcon(QIcon(resource_path(r'ico\fullscreen.png'))) self.screenBtn.setIconSize(QSize(19, 19)) self.screenBtn.clicked.connect(self.full_screen) self.screenBtn.setToolTip('Переключить на полноэкранный размер') self.screenBtn.setToolTipDuration(2500) # ----- кнопки для пустых мест ----- # # создание button (для окна настроек) self.imageBtn = QPushButton() self.imageBtn.setIcon(QIcon(resource_path(r'ico\photo.png'))) self.imageBtn.setToolTip( 'Открывает второе окно которое позволяет взимодействовать с изображениями' ) self.imageBtn.setIconSize((QSize(18, 18))) self.imageBtn.setEnabled(True) self.imageBtn.setStyleSheet(config) self.themeBtn = Switch(thumb_radius=11, track_radius=8) self.themeBtn.setObjectName('default') self.themeBtn.setToolTip('Изменить задний фон') self.themeBtn.clicked.connect(self.change_to_dark_theme) self.blankBtn = QPushButton() self.blankBtn.setEnabled(False) self.blankBtn.setStyleSheet(conf_for_blank) # --------------------------------------- # # создание slider'а self.slider = MySlider(orient=Qt.Horizontal) self.slider.sliderMoved.connect(self.set_position) # создания slider для volume self.hslider = MySlider(orient=Qt.Horizontal) self.hslider.setRange(0, 100) self.hslider.setMaximumHeight(7) self.hslider.sliderMoved.connect(self.set_volume_position) self.hslider.setMaximumWidth(80) self.hslider.setSliderPosition(100) # создания label'а self.label1 = QLabel('0:00 /') self.label1.setToolTip('Прошло времени') self.label1.setFont(QFont('SansSerif', 8, QFont.Bold)) self.label2 = QLabel('0:00') self.label2.setToolTip('Общая продолжительность') self.label2.setFont(QFont('SansSerif', 8, QFont.Bold)) # создание hbox layout hboxLayout = QHBoxLayout() hboxLayout.setContentsMargins(0, 0, 0, 0) # создание hbox2 layout hboxLayout2 = QHBoxLayout() hboxLayout.setContentsMargins(0, 0, 0, 0) # добавления виджетов в hbox2 layout hboxLayout2.addWidget(self.label1) hboxLayout2.addWidget(self.label2) hboxLayout2.addWidget(self.slider) hboxLayout2.addWidget(self.volumeBtn) hboxLayout2.addWidget(self.hslider) # добавления виджетов в hbox layout hboxLayout.addWidget(self.themeBtn) hboxLayout.addWidget(self.blankBtn) hboxLayout.addWidget(openBtn) hboxLayout.addWidget(self.backBtn) hboxLayout.addWidget(self.playBtn) hboxLayout.addWidget(self.forwardBtn) hboxLayout.addWidget(self.imageBtn) hboxLayout.addWidget(self.screenBtn) # self.frame = MyFrame() vboxLayout = QVBoxLayout() # vboxLayout.addWidget(MyFrame()) vboxLayout.addWidget(videowidget) vboxLayout.addLayout(hboxLayout2) vboxLayout.addLayout(hboxLayout) self.setLayout(vboxLayout) self.mediaPlayer.setVideoOutput(videowidget) # обработчики медиа сигналов self.mediaPlayer.stateChanged.connect(self.media_state_changed) self.mediaPlayer.positionChanged.connect(self.position_changed) self.mediaPlayer.durationChanged.connect(self.duration_changed) self.mediaPlayer.volumeChanged.connect(self.set_volume_position) self.mediaPlayer.durationChanged.connect(self.duration_volume) # Несколько функций которые вызываются во время взаимодействия с клавишами для удобства self.volumeMinSc = QShortcut(QKeySequence('Down'), self) self.volumeMinSc.activated.connect(self.min_volume) self.volumePlusSc = QShortcut(QKeySequence('Up'), self) self.volumePlusSc.activated.connect(self.plus_volume) self.forwardSc = QShortcut(QKeySequence('Right'), self) self.forwardSc.activated.connect(self.go_forward_with_key) self.backSc = QShortcut(QKeySequence('Left'), self) self.backSc.activated.connect(self.go_back_with_key) self.fullscreenSc = QShortcut(QKeySequence('F'), self) self.fullscreenSc.activated.connect(self.full_screen) def dragEnterEvent(self, event): if event.mimeData().hasImage: event.accept() else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasImage: event.accept() else: event.ignore() def dropEvent(self, event): if event.mimeData().hasImage: event.setDropAction(Qt.CopyAction) file_path = event.mimeData().urls()[0].toLocalFile() self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(file_path))) self.playBtn.setEnabled(True) self.backBtn.setEnabled(True) self.forwardBtn.setEnabled(True) event.accept() else: event.ignore() # ------------------------------ # Функция открытия файла def open_file(self): # global filename filename, _ = QFileDialog.getOpenFileName(self) if filename != '': self.mediaPlayer.setMedia( QMediaContent(QUrl.fromLocalFile(filename))) self.playBtn.setEnabled(True) self.backBtn.setEnabled(True) self.forwardBtn.setEnabled(True) # -------------------------------------- # Функция запуска и паузы видеоплеера def play_video(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() else: self.mediaPlayer.play() def go_back_with_key(self): pos = self.mediaPlayer.position() pos = min(pos - 1000, pos) self.mediaPlayer.setPosition(pos) def go_forward_with_key(self): pos = self.mediaPlayer.position() pos = max(pos + 1000, pos) self.mediaPlayer.setPosition(pos) # -------------------------------------- def blef_win(self): # Сокрытие вернего слоя Layout'a self.label1.hide() self.label2.hide() self.slider.hide() self.volumeBtn.hide() self.hslider.hide() # Сокрытие нижнего слоя Layout'a openBtn.hide() self.imageBtn.hide() self.backBtn.hide() self.playBtn.hide() self.forwardBtn.hide() self.screenBtn.hide() self.themeBtn.hide() # -------------------------------------- def blef_win_on(self): # 'Показать' верний слой Layout'a self.label1.setVisible(True) self.label2.setVisible(True) self.slider.setVisible(True) self.volumeBtn.setVisible(True) self.hslider.setVisible(True) # 'Показать' нижний слой Layout'a openBtn.setVisible(True) self.imageBtn.setVisible(True) self.backBtn.setVisible(True) self.playBtn.setVisible(True) self.forwardBtn.setVisible(True) self.screenBtn.setVisible(True) self.themeBtn.setVisible(True) # -------------------------------------- def change_to_dark_theme(self): dark = '#3C3F41' new_dark_config = ''' QPushButton{ border: none; margin: 0px; padding: 0px; background-color: %s; } QPushButton:hover{ background-color: #B4B4B4 ; border-radius:7px; width: 30px; } ''' % dark config = '''QPushButton{ border: none; margin: 0px; padding: 0px; background-color:#F0F0F0; } QPushButton:hover{ background-color: #B4B4B4; border-radius:7px; width: 30px; } ''' if self.themeBtn.objectName() == 'default': self.setStyleSheet(f"background-color: {dark};") self.imageBtn.setStyleSheet(new_dark_config) self.themeBtn.setStyleSheet(new_dark_config) self.themeBtn.setIcon(QIcon(resource_path(r'ico/default.png'))) self.themeBtn.setIconSize((QSize(18, 18))) self.screenBtn.setStyleSheet(new_dark_config) self.playBtn.setStyleSheet(new_dark_config) self.backBtn.setStyleSheet(new_dark_config) self.forwardBtn.setStyleSheet(new_dark_config) self.volumeBtn.setStyleSheet(new_dark_config) self.blankBtn.setStyleSheet(new_dark_config) openBtn.setStyleSheet(new_dark_config) self.themeBtn.setObjectName('dark') else: self.setStyleSheet(f"background-color: #F0F0F0;") self.imageBtn.setStyleSheet(config) self.themeBtn.setStyleSheet(config) self.themeBtn.setIcon(QIcon(resource_path(r'ico/dark_mode.png'))) self.themeBtn.setIconSize((QSize(18, 18))) self.screenBtn.setStyleSheet(config) self.playBtn.setStyleSheet(config) self.backBtn.setStyleSheet(config) self.forwardBtn.setStyleSheet(config) self.volumeBtn.setStyleSheet(config) self.blankBtn.setStyleSheet(config) openBtn.setStyleSheet(config) self.themeBtn.setObjectName('default') # Функия для полноэкранного режима # -------------------------------------- def full_screen(self): if self.screenBtn.objectName() == 'fullscreen': self.showMaximized() self.screenBtn.setObjectName('normal_screen') # self.screenBtn.setToolTip('Возвращения окна стандартного режима') self.screenBtn.setIcon(QIcon( resource_path(r'ico\norm_screen.png'))) else: self.screenBtn.setObjectName('fullscreen') self.screenBtn.setIcon(QIcon(resource_path(r'ico\fullscreen.png'))) # self.screenBtn.setToolTip('Переключить на полноэкранный размер') self.showNormal() # Функия для кнопки громкости (проявляет слайдер) def volume(self): if self.volumeBtn.objectName() == 'volume_btn': self.mediaPlayer.setMuted(True) self.volumeBtn.setObjectName('btn') self.volumeBtn.setIcon(QIcon(resource_path(r'ico\vol_muted.png'))) else: self.volumeBtn.setObjectName('volume_btn') self.mediaPlayer.setMuted(False) self.volumeBtn.setIcon(QIcon(resource_path(r'ico\volume1.png'))) # Проверка громкости def volume_check(self): if self.mediaPlayer.volume() == 0: self.volumeBtn.setIcon(QIcon(resource_path(r'ico\vol_muted.png'))) if self.mediaPlayer.isMuted(): self.volumeBtn.setIcon(QIcon(resource_path(r'ico\vol_muted.png'))) # Функция для снижения громкости def min_volume(self): vol = self.mediaPlayer.volume() vol = min(vol - 5, 100) self.mediaPlayer.setVolume(vol) volume_state = self.hslider.sliderPosition() volume_state = min(volume_state - 5, self.hslider.sliderPosition()) self.hslider.setSliderPosition(volume_state) if self.mediaPlayer.volume() == 0 or self.mediaPlayer.isMuted(): self.volumeBtn.setIcon(QIcon(resource_path(r'ico\vol_muted.png'))) else: self.volumeBtn.setIcon(QIcon(resource_path(r'ico\volume1.png'))) # Функция для увелечения громкости def plus_volume(self): vol = self.mediaPlayer.volume() vol = max(vol + 5, 0) self.mediaPlayer.setVolume(vol) volume_state = self.hslider.sliderPosition() volume_state = max(volume_state + 5, self.hslider.sliderPosition()) self.hslider.setSliderPosition(volume_state) # Функция которая меняет состояние кнопок def media_state_changed(self): if self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.playBtn.setIcon(QIcon(resource_path(r'ico\pause.png'))) self.playBtn.setIconSize(QSize(40, 40)) else: self.playBtn.setIcon(QIcon(resource_path(r'ico\play.png'))) self.playBtn.setIconSize(QSize(40, 40)) # Функция которая отвечает за перемотку с помощью слайдера и которая выводит прошедшее время с начала записи def position_changed(self, position): self.slider.setValue(position) self.label1.setText( '%d:%02d /' % (int(position / 60000), int((position / 1000) % 60))) # Функция отвечающая за нахождения общей продолжительности записи и ввывод ее в надпись def duration_changed(self, duration): self.slider.setRange(0, duration) durations = self.mediaPlayer.duration() self.label2.setText( '%d:%02d' % (int(durations / 60000), int((durations / 1000) % 60))) # передает значение позиции в медиаплеер def set_position(self, position): self.mediaPlayer.setPosition(position) # Обработчик ошибки def handle_errors(self): self.playBtn.setEnabled(False) # Функция управляющая за передачу в слайдер громкости def position_volume(self, position): self.hslider.setValue(position) # Функция задающаю общую грумкость def duration_volume(self): self.hslider.setRange(0, 100) # Функция для регулирования громкости def set_volume_position(self, position): self.mediaPlayer.setVolume(position) if self.mediaPlayer.volume() == 0 or self.mediaPlayer.isMuted(): self.volumeBtn.setIcon(QIcon(resource_path(r'ico\vol_muted.png'))) elif self.mediaPlayer.volume() != 0 or self.mediaPlayer.isMuted(): self.volumeBtn.setIcon(QIcon(resource_path(r'ico\volume1.png'))) # перемотка назад на 10сек def go_back(self): pos = self.mediaPlayer.position() pos = min(pos - 10000, pos) self.mediaPlayer.setPosition(pos) # перемотка вперед на 10сек def go_forward(self): pos = self.mediaPlayer.position() pos = max(pos + 10000, pos) self.mediaPlayer.setPosition(pos)