def test(): url = QUrl.fromLocalFile("D:/test/1.mov") content = QMediaContent(url) player = QMediaPlayer() player.setMedia(content) # player.setVolume(Sound_level) player.play()
class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.resize(600, 400) self.media_player = QMediaPlayer(self, QMediaPlayer.VideoSurface) self.video_widget = QVideoWidget(self) self.setCentralWidget(self.video_widget) def showEvent(self, event) -> None: if sys.platform in ['linux', 'darwin']: media_content = QMediaContent( QUrl.fromLocalFile( QFileInfo( './../example_data/sample.mp4').absoluteFilePath())) else: media_content = QMediaContent( QUrl.fromLocalFile( QFileInfo( './../example_data/pusheen.gif').absoluteFilePath())) self.media_player.setMedia(media_content) self.media_player.setVideoOutput(self.video_widget) self.video_widget.show() self.video_widget.update() self.media_player.setPosition(0) self.media_player.play()
def test2(): url = QUrl.fromLocalFile("D:/test/2.mp4") content = QMediaContent(url) player = QMediaPlayer() vw = QVideoWidget() vw.show() player.play() player.setVideoOutput(vw) player.setMedia(content)
class MainWindow(QObject): #class constructor def __init__(self, ui_file, parent=None): #reference to our music player self.music_player = QMediaPlayer() self.music_player.setVolume(100) #call parent QObject constructor super(MainWindow, self).__init__(parent) #load the UI file into Python ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) loader = QUiLoader() self.window = loader.load(ui_file) ui_file.close() volume_slider = self.window.findChild(QSlider, 'volume_slider') volume_slider.valueChanged.connect(self.volumeChanged) open_action = self.window.findChild(QAction, 'action_open') open_action.triggered.connect(self.open_action_triggered) quit_action = self.window.findChild(QAction, 'action_quit') quit_action.triggered.connect(self.quit_action_triggered) play_button = self.window.findChild(QPushButton, 'play_button') play_button.clicked.connect(self.play_button_clicked) pause_button = self.window.findChild(QPushButton, 'pause_button') pause_button.clicked.connect(self.pause_button_clicked) #show window to user self.window.show() def open_action_triggered(self): file_name = QFileDialog.getOpenFileName(self.window) self.music_player.setMedia(QUrl.fromLocalFile(file_name[0])) def pause_button_clicked(self): self.music_player.pause() def quit_action_triggered(self): self.window.close() def play_button_clicked(self): self.music_player.play() def volumeChanged(self): volume = self.window.findChild(QSlider, 'volume_slider').value() self.music_player.setVolume(volume)
def notify(self): if not self.notification: return if self.notification_tray: self.tray.showMessage( "Finished", "Le décompte est terminé", self.style().standardIcon(QStyle.SP_MessageBoxInformation)) if self.notification_sound: test = QMediaPlayer() test.setMedia(QUrl.fromLocalFile(self.notification_soundfile)) test.play() if self.notification_popup: QMessageBox.information(self, "Finished", "Le décompte est terminé")
def _set_sound_source(alias): solution = 2 if solution == 0: # qrc, MediaPlayer() sound = QMediaPlayer() sound.setMedia(QUrl('qrc:/' + alias)) elif solution == 1: # absoluteFilePath(), MediaPlayer() path = QFileInfo('sounds/' + alias + '.wav').absoluteFilePath() sound = QMediaPlayer() sound.setMedia(QUrl(path)) elif solution == 2: # qrc, QSound() sound = QSound('qrc:/' + alias) return sound
def __int__(self): super(MyApp, self).__init__() self.master_layout = QVBoxLayout() player = QMediaPlayer() item = QGraphicsVideoItem() player.setVideoOutput(item) player.setMedia((QUrl("D:/test/1.mov"))) graphicsView = MainView() graphicsView.scene().addItem(item) graphicsView.show() self.master_layout.addWidget(graphicsView) self.setLayout(self.master_layout) player.play()
class App(QApplication): def __init__(self, sys_argv): super().__init__(sys_argv) # Show main window self.view = QMainWindow() self.centralWidget = QWidget(self.view) self.gridLayout = QGridLayout(self.centralWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.video_item = QVideoWidget() self.gridLayout.addWidget(self.video_item) self.view.setCentralWidget(self.centralWidget) self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.grabber = VideoFrameGrabber(self.video_item, self) self.mediaPlayer.setVideoOutput(self.grabber) self.grabber.frameAvailable.connect(self.process_frame) self.mediaPlayer.durationChanged.connect(self.update_duration) self.mediaPlayer.positionChanged.connect(self.update_slider_position) local = QUrl.fromLocalFile('D:\\SampleData\\albamonSample.mp4') media = QMediaContent(local) self.mediaPlayer.setMedia(media) self.mediaPlayer.play() self.view.show() def process_frame(self, image): # Save image here image.save('D:\\SampleData/temp/{}.jpg'.format(str(uuid.uuid4()))) def update_duration(self): pass def update_slider_position(self): pass
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.sound = QMediaPlayer() self.executeToken = False self.setAcceptDrops(True) self.installEventFilter(self) if os.path.exists('config.json'): with codecs.open('config.json', 'r', 'utf_8_sig') as config: config = config.read() self.config = json.loads(config) else: self.config = { 'room_url': '', 'bgm_path': '', 'gif_path': '', 'font_color': '#000000', 'font_name': 'yahei', 'font_size': '10', 'font_bold': '0', 'font_italic': '0' } self.GIFWidget = GIFWidget(self.config['gif_path']) self.GIFWidget.finish.connect(self.animateFinish) self.setWindowTitle('B站直播打赏感谢机 测试版 (by up 执鸣神君)') self.main_widget = QWidget() self.main_widget.setAcceptDrops(True) self.setCentralWidget(self.main_widget) layout = QGridLayout() self.main_widget.setLayout(layout) roomIDLabel = QLabel('主播房间地址') roomIDLabel.setAlignment(Qt.AlignCenter) layout.addWidget(roomIDLabel, 0, 0, 1, 1) self.roomURLEdit = QLineEdit(self.config['room_url']) layout.addWidget(self.roomURLEdit, 0, 2, 1, 5) bgmButton = QPushButton('选择答谢音效') bgmButton.clicked.connect(self.selectBGM) layout.addWidget(bgmButton, 1, 0, 1, 1) self.bgmEdit = QLineEdit(self.config['bgm_path']) self.sound.setMedia(QUrl.fromLocalFile(self.config['bgm_path'])) layout.addWidget(self.bgmEdit, 1, 2, 1, 5) fontButton = QPushButton('设置字体样式') fontButton.clicked.connect(self.getFont) layout.addWidget(fontButton, 2, 0, 1, 1) self.font = QFont(self.config['font_name'], int(self.config['font_size'])) if self.config['font_bold'] == '1': self.font.setBold(True) if self.config['font_italic'] == '1': self.font.setItalic(True) self.color = self.config['font_color'] self.fontLabel = QLabel('感谢甲鱼投喂的100个小心心') self.fontLabel.setFont(self.font) self.fontLabel.setStyleSheet('color:' + self.color) self.GIFWidget.setFont(self.font) self.GIFWidget.setColor(self.color) layout.addWidget(self.fontLabel, 2, 2, 1, 5) self.filterToken = True self.filterButton = QPushButton('过滤银币礼物') self.filterButton.setStyleSheet('background-color:#3daee9') self.filterButton.clicked.connect(self.changeFilter) layout.addWidget(self.filterButton, 3, 0, 1, 1) self.preview = previewLabel('点击或拖入要播放的答谢gif动图') self.preview.click.connect(self.click) if self.config['gif_path']: movie = QMovie(self.config['gif_path']) self.preview.setMovie(movie) movie.start() layout.addWidget(self.preview, 4, 0, 5, 7) self.testButton = QPushButton('测试一下') self.testButton.clicked.connect(self.testAnimate) self.testButton.setFixedSize(200, 65) layout.addWidget(self.testButton, 9, 0, 2, 3) self.startButton = QPushButton('开始捕获') self.startButton.clicked.connect(self.startMonitor) self.startButton.setFixedSize(200, 65) layout.addWidget(self.startButton, 9, 4, 2, 3) def changeFilter(self): if self.filterToken: self.filterButton.setText('显示所有礼物') self.filterButton.setStyleSheet('background-color:#31363b') else: self.filterButton.setText('过滤银币礼物') self.filterButton.setStyleSheet('background-color:#3daee9') self.filterToken = not self.filterToken try: self.remoteThread.setFilter(self.filterToken) except: pass def selectBGM(self): if not os.path.exists('bgm'): os.mkdir('bgm') filePath = QFileDialog.getOpenFileName(self, "请选择bgm文件", 'bgm', "*.mp3 *.wav")[0] if filePath: fileName = os.path.split(filePath)[1] if not os.path.exists(r'bgm/%s' % fileName): shutil.copy(filePath, 'bgm') self.bgmEdit.setText(filePath) self.sound.setMedia(QUrl.fromLocalFile(filePath)) def click(self): filePath = QFileDialog.getOpenFileName(self, "请选择gif文件", 'gif', "*.gif")[0] if filePath: self.openFile(filePath) def openFile(self, filePath): if filePath.endswith('.gif'): fileName = os.path.split(filePath)[1] if not os.path.exists('gif'): os.mkdir('gif') if not os.path.exists(r'gif/%s' % fileName): shutil.copy(filePath, 'gif') movie = QMovie(filePath) self.preview.setMovie(movie) movie.start() self.GIFWidget.setGIFPath(filePath) self.config['gif_path'] = r'%s/gif/%s' % (os.getcwd(), fileName) def dragEnterEvent(self, QDragEnterEvent): QDragEnterEvent.accept() def dropEvent(self, QEvent): if QEvent.mimeData().hasUrls: self.openFile(QEvent.mimeData().urls()[0].toLocalFile()) def closeEvent(self, QCloseEvent): self.GIFWidget.close() self.config['room_url'] = self.roomURLEdit.text() self.config['bgm_path'] = self.bgmEdit.text() with codecs.open('config.json', 'w', 'utf_8_sig') as config: config.write(json.dumps(self.config, ensure_ascii=False)) def getFont(self): status, font = QFontDialog.getFont(self.font) if status: font = QFontInfo(font) fontName = font.family() fontSize = font.pointSize() fontBold = font.bold() fontItalic = font.italic() self.font = QFont(fontName, fontSize) if fontBold: self.font.setBold(True) if fontItalic: self.font.setItalic(True) self.config['font_name'] = fontName self.config['font_size'] = fontSize self.config['font_bold'] = '1' if fontBold else '0' self.config['font_italic'] = '1' if fontItalic else '0' self.fontLabel.setFont(self.font) self.GIFWidget.setFont(self.font) color = QColorDialog.getColor(self.color) if color.isValid(): self.color = color.name() self.config['font_color'] = self.color self.fontLabel.setStyleSheet('color:' + self.color) self.GIFWidget.setColor(self.color) def testAnimate(self): if self.bgmEdit.text(): self.sound.play() self.GIFWidget.animationTimer.start() def playAnimate(self, giftInfo): if self.bgmEdit.text(): self.sound.play() self.GIFWidget.setGiftInfo(giftInfo) self.GIFWidget.frame = 180 self.GIFWidget.animationTimer.start() def animateFinish(self): self.sound.stop() def startMonitor(self): if not self.executeToken: self.remoteThread = remoteThread(self.roomURLEdit.text()) self.remoteThread.giftInfo.connect(self.playAnimate) self.remoteThread.start() self.executeToken = True self.GIFWidget.executeToken = True self.GIFWidget.setWindowOpacity(0) self.testButton.setEnabled(False) self.startButton.setStyleSheet('background-color:#3daee9') self.startButton.setText('停止捕获') else: self.remoteThread.terminate() self.remoteThread.quit() self.remoteThread.wait() self.executeToken = False self.GIFWidget.executeToken = False self.GIFWidget.setWindowOpacity(1) self.testButton.setEnabled(True) self.startButton.setStyleSheet('background-color:#31363b') self.startButton.setText('开始捕获')
class EditorWidget(QWidget): """Widget which contain the editor.""" def __init__(self, plugin_manager): super(EditorWidget, self).__init__() os.environ[ 'QT_MULTIMEDIA_PREFERRED_PLUGINS'] = 'windowsmediafoundation' self.plugin_manager = plugin_manager #parent layout self.v_box = QVBoxLayout() self.h_box = QHBoxLayout() # parent splitter for the text and numbers self.text_h_box = QSplitter(Qt.Horizontal) self.text_h_box.splitterMoved.connect(self.on_text_changed) self.settings = QSettings(c.SETTINGS_PATH, QSettings.IniFormat) self.keyboard_settings = QSettings(c.KEYBOARD_SETTINGS_PATH, QSettings.IniFormat) self.theme = self.settings.value(c.THEME, defaultValue=c.THEME_D) # font settings self.font = QFont( self.settings.value(c.FONT, defaultValue="Arial", type=str)) self.font.setPointSize( self.settings.value(c.FONT_SIZE, defaultValue=16, type=int)) # the text widget itself self.text = QPlainTextEdit() self.text.setFont(self.font) self.text.textChanged.connect(self.on_text_changed) self.text.setFocusPolicy(Qt.StrongFocus) # the number text widget to show the row numbers self.numbers = QPlainTextEdit() self.numbers.setFont(self.font) self.numbers.setReadOnly(True) self.numbers.setMinimumWidth(20) self.numbers.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.numbers.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.numbers.setLineWrapMode(QPlainTextEdit.NoWrap) self.numbers.setFocusPolicy(Qt.NoFocus) self.numbers.setFrameStyle(QFrame.NoFrame) self.numbers.setStyleSheet("background-color: rgba(0,0,0,0%)") # sync the text widget and number widget self.text_bar = self.text.verticalScrollBar() self.number_bar = self.numbers.verticalScrollBar() #self.number_bar.valueChanged.connect(self.text_bar.setValue) self.text_bar.valueChanged.connect(self.number_bar.setValue) # add them into their layout self.text_h_box.addWidget(self.numbers) self.text_h_box.addWidget(self.text) self.text_h_box.setSizes([10, 700]) # layout which holds the media controls in the bottom self.media_controls = QHBoxLayout() self.media_controls_settings = QVBoxLayout() self.media_controls_slider_h_box = QHBoxLayout() # direct player controls self.btn_size = 75 self.play_icon = QIcon( os.path.join(c.ICON_PATH, self.theme, "play.png")) self.pause_icon = QIcon( os.path.join(c.ICON_PATH, self.theme, "pause.png")) self.play_btn = QPushButton(icon=self.play_icon) self.play_btn.clicked.connect(self.on_play) self.play_btn.setFixedSize(self.btn_size, self.btn_size) self.play_btn.setIconSize(QSize(self.btn_size, self.btn_size)) self.play_btn.setFlat(True) self.play_btn.setShortcut(QKeySequence().fromString( self.keyboard_settings.value(c.PLAY_PAUSE_KEY, defaultValue=""))) self.forward_btn = QPushButton( icon=QIcon(os.path.join(c.ICON_PATH, self.theme, "forward.png"))) self.forward_btn.clicked.connect(self.on_forward) self.forward_btn.setFixedSize(self.btn_size, self.btn_size) self.forward_btn.setIconSize(QSize(self.btn_size, self.btn_size)) self.forward_btn.setFlat(True) self.forward_btn.setShortcut(QKeySequence().fromString( self.keyboard_settings.value(c.FORWARD_KEY, defaultValue=""))) self.backward_btn = QPushButton( icon=QIcon(os.path.join(c.ICON_PATH, self.theme, "backward.png"))) self.backward_btn.clicked.connect(self.on_backward) self.backward_btn.setFixedSize(self.btn_size, self.btn_size) self.backward_btn.setIconSize(QSize(self.btn_size, self.btn_size)) self.backward_btn.setFlat(True) self.backward_btn.setShortcut(QKeySequence().fromString( self.keyboard_settings.value(c.BACKWARDS_KEY, defaultValue=""))) # add them to the layout self.media_controls.addStretch() self.media_controls.addWidget(self.backward_btn) self.media_controls.addWidget(self.play_btn) self.media_controls.addWidget(self.forward_btn) self.media_controls.addStretch(4) # slider which shows the current time self.time_slider = QSlider(Qt.Horizontal) self.time_slider.sliderMoved.connect(self.on_time_slider_moved) # label on the right of the slider, which shows the current time self.time_label = QLabel("00:00/00:00") self.media_controls_slider_h_box.addWidget(self.time_slider) self.media_controls_slider_h_box.addWidget(self.time_label) # icons for the other sliders self.vol_icon = QIcon( os.path.join(c.ICON_PATH, self.theme, "volume.png")).pixmap(QSize(32, 32)) self.rate_icon = QIcon( os.path.join(c.ICON_PATH, self.theme, "playbackrate.png")).pixmap(QSize(32, 32)) self.rewind_icon = QIcon( os.path.join(c.ICON_PATH, self.theme, "time.png")).pixmap(QSize(32, 32)) # display the icons through labels self.vol_icon_label = QLabel() self.vol_icon_label.setPixmap(self.vol_icon) self.rate_icon_label = QLabel() self.rate_icon_label.setPixmap(self.rate_icon) self.rewind_rewind_label = QLabel() self.rewind_rewind_label.setPixmap(self.rewind_icon) # init of the other sliders self.vol_slider = QSlider(Qt.Horizontal) self.vol_slider.sliderMoved.connect(self.on_vol_slider_moved) self.vol_slider.setFixedWidth(250) self.vol_slider.setRange(1, 100) self.rate_slider = QSlider(Qt.Horizontal) self.rate_slider.sliderMoved.connect(self.on_rate_slider_moved) self.rate_slider.setFixedWidth(250) self.rate_slider.setRange(1, 20) self.rewind_time = 10 self.rewind_slider = QSlider(Qt.Horizontal) self.rewind_slider.sliderMoved.connect(self.on_rewind_slider_moved) self.rewind_slider.setFixedWidth(250) self.rewind_slider.setRange(1, 60) self.rewind_slider.setValue(self.rewind_time) # labels for the values self.vol_label = QLabel() self.rate_label = QLabel() self.rewind_label = QLabel() # create hbox for each of the three sliders self.vol_h_box = QHBoxLayout() self.vol_h_box.addWidget(self.vol_label) self.vol_h_box.addWidget(self.vol_slider) self.vol_h_box.addWidget(self.vol_icon_label) self.rate_h_box = QHBoxLayout() self.rate_h_box.addWidget(self.rate_label) self.rate_h_box.addWidget(self.rate_slider) self.rate_h_box.addWidget(self.rate_icon_label) self.rewind_h_box = QHBoxLayout() self.rewind_h_box.addWidget(self.rewind_label) self.rewind_h_box.addWidget(self.rewind_slider) self.rewind_h_box.addWidget(self.rewind_rewind_label) # group them together in a vlayout self.media_controls_settings.addLayout(self.vol_h_box) self.media_controls_settings.addLayout(self.rewind_h_box) self.media_controls_settings.addLayout(self.rate_h_box) # add this layout to the layout which already contains the buttons self.media_controls.addLayout(self.media_controls_settings) self.word_by_word_actions = QListWidget() self.word_by_word_actions.setMaximumWidth(150) self.h_box.addWidget(self.text_h_box) self.h_box.addWidget(self.word_by_word_actions) # group all ungrouped layouts and widgets to the parent layout self.v_box.addLayout(self.h_box, 10) self.v_box.addLayout(self.media_controls_slider_h_box, 1) self.v_box.addLayout(self.media_controls, 1) # set parent layout self.setLayout(self.v_box) # init media_player self.media_player = QMediaPlayer() self.video_widget = QVideoWidget() self.video_widget.setGeometry(200, 200, 500, 300) self.video_widget.setWindowTitle("Output") self.media_player.setVideoOutput(self.video_widget) self.media_player.positionChanged.connect(self.on_position_change) self.media_player.durationChanged.connect(self.on_duration_change) self.vol_slider.setValue(self.media_player.volume()) self.rate_slider.setValue(int(self.media_player.playbackRate() * 10)) self.on_vol_slider_moved(self.media_player.volume()) self.on_rate_slider_moved(self.media_player.playbackRate() * 10) self.on_rewind_slider_moved(self.rewind_time) self.activate_text_modules = False self.get_text_modules() self.text_option_on = QTextOption() self.text_option_on.setFlags( QTextOption.ShowTabsAndSpaces | QTextOption.ShowLineAndParagraphSeparators) self.text_option_off = QTextOption() self.transcription_meta_data = None self.word_pos = -1 self.word_start_time = None self.word_end_time = None self.tcf_highlight = QTextCharFormat() self.tcf_highlight.setBackground(Qt.red) self.tcf_normal = QTextCharFormat() self.tcf_normal.setBackground(Qt.transparent) self.show_empty_buttons = self.settings.value(c.SHOW_EMPTY_BUTTONS, defaultValue=True, type=bool) def on_position_change(self, position): """Is executed when media is played (position is changed) Args: position: Current position (ms) of the media player. """ self.time_slider.setValue(position) self.time_label.setText( create_time_string(position, self.media_player.duration())) if self.word_end_time is None: return if position > self.word_end_time: self.on_play() self.word_start_time = None self.word_end_time = None def on_duration_change(self, duration): """Is executed when duration of the media changes. Args: duration: duration of the media. """ self.time_slider.setRange(0, duration) self.time_label.setText( create_time_string(0, self.media_player.duration())) def on_time_slider_moved(self, value): """Is executed when the time slider was moved. Args: value: current value of the slider. """ self.media_player.setPosition(value) def on_vol_slider_moved(self, value): """Is executed when the volume slider is moved. Args: value: current value of the slider. """ self.media_player.setVolume(value) self.vol_label.setText(str(value) + "%") def on_rate_slider_moved(self, value): """Is executed when the rate slider is moved. Args: value: current value of the slider. """ self.media_player.setPlaybackRate(value / 10) self.rate_label.setText(str(value / 10) + "x") def on_rewind_slider_moved(self, value): """Is executed when the rewind slider is moved. Args: value: current value of the slider. """ self.rewind_time = value self.rewind_label.setText(str(value) + "s") def on_play(self): """Is executed when the play or pause button is pressed.""" if self.media_player.state() == QMediaPlayer.PlayingState: self.media_player.pause() self.play_btn.setIcon(self.play_icon) else: self.media_player.play() self.play_btn.setIcon(self.pause_icon) def on_forward(self): """Is executed when the forward button is pressed.""" self.media_player.setPosition(self.media_player.position() + self.rewind_time * 1000) def on_backward(self): """Is executed when the backward button is pressed.""" self.media_player.setPosition(self.media_player.position() - self.rewind_time * 1000) def on_text_changed(self): """Is executed when the text changed Calculates the line numbers and sets the text modules if activated. """ lines = int( self.text.document().documentLayout().documentSize().height()) self.numbers.setPlainText("") text = "" for i in range(1, lines + 1): text = text + str(i) + "\n" self.numbers.setPlainText(text) self.number_bar.setSliderPosition(self.text_bar.sliderPosition()) new_text = self.text.toPlainText() if self.activate_text_modules == True: for key in self.text_modules.keys(): to_replace = " " + key + " " to_replace_with = " " + self.text_modules[key] + " " new_text = new_text.replace(to_replace, to_replace_with) if self.text.toPlainText() != new_text: old_pos = self.text.textCursor().position() self.text.setPlainText(new_text) cursor = self.text.textCursor() cursor.setPosition(old_pos, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.EndOfWord) cursor.movePosition(QTextCursor.NextCharacter) self.text.setTextCursor(cursor) def show_video(self): """Shows or hides the video feed.""" if self.video_widget.isVisible(): self.video_widget.hide() else: self.video_widget.show() def open_project(self, project_folder_path): """Opens a project. Args: project_folder_path: folder of the project which should be opened. """ self.project_folder_path = project_folder_path self.media_file = file_util.get_file(self.project_folder_path, c.CON_COPY_POSTFIX) if self.media_file is None: self.hide() return self.media_player.setMedia( QMediaContent(QUrl.fromLocalFile(self.media_file))) self.transcription_path = file_util.get_file(self.project_folder_path, c.TRANSCRIPTION) if self.transcription_path is None: self.hide() return with open(self.transcription_path, 'r') as f: text = f.read() self.text.setPlainText(text) self.transcription_meta_data = file_util.get_value_from_shelve( self.project_folder_path, c.TRANSCRIPTION_META_DATA) print(self.transcription_meta_data) def change_font(self, new_font, new_size): """Changes the font. Args: new_font: Name of the new font. new_size: New font size. """ self.font = QFont(new_font) self.font.setPointSize(int(new_size)) self.text.setFont(self.font) self.numbers.setFont(self.font) self.settings.setValue(c.FONT_SIZE, int(new_size)) self.settings.setValue(c.FONT, new_font) def get_text_modules(self): """Gets the saved text_modules from the settings.""" self.text_modules = self.settings.value(c.TEXT_MODULES, defaultValue={}) def show_special_characters(self, bol): """Displays the special characters. Args: bol: true or false. """ if bol: self.text.document().setDefaultTextOption(self.text_option_on) else: self.text.document().setDefaultTextOption(self.text_option_off) def on_word_by_word(self): """Selects the next or first word in the on word by word editing mode. For that purpose th word_postion is increased and the next word is marked via the textcursor. If everything works correctly the population of the list will be started. """ self.word_pos += 1 #if self.media_player.state() == QMediaPlayer.PlayingState: # return if self.word_pos > len(self.text.toPlainText().split()) - 1: self.reset_word_by_word() return cursor = self.text.textCursor() if self.word_pos == 0: self.show_empty_buttons = self.settings.value(c.SHOW_EMPTY_BUTTONS, defaultValue=True, type=bool) cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.StartOfWord, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) self.text.setEnabled(False) else: cursor.movePosition(QTextCursor.NextWord, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) self.text.setTextCursor(cursor) selected_word = cursor.selectedText() if not selected_word: self.word_pos -= 1 self.on_word_by_word() return # change to find all meta data meta_data_with_word = self.find_meta_data(selected_word) self.populate_word_actions(selected_word, meta_data_with_word) def on_word_by_word_prev(self): """Same as word for word but selects to the previous word.""" if self.word_pos < 1: return self.word_pos -= 2 cursor = self.text.textCursor() count = 0 cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.StartOfWord, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) while count < self.word_pos: cursor.movePosition(QTextCursor.NextWord, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) count += 1 self.text.setTextCursor(cursor) self.on_word_by_word() def reset_word_by_word(self): """Resets the word by word editing mode and goes back to the normal editing.""" self.word_pos = -1 self.play_to = -1 self.text.setEnabled(True) self.word_by_word_actions.clear() cleaned = self.text.textCursor() cleaned.clearSelection() self.text.setTextCursor(cleaned) def populate_word_actions(self, selected, word_meta_data): """Calls the plugin_manager to get alle the word for word buttons and initalize the hear again buttons. Args: selected: The selected word. word_meta_data: The meta_data fr the word. """ self.word_by_word_actions.clear() if self.word_pos == len(self.text.toPlainText().split()): return self.plugin_manager.get_word_by_word_actions(selected, word_meta_data, self.word_pos) btns = [] for meta_data in word_meta_data: media_btn = HearButton(self, meta_data) btns.append(media_btn) self.add_new_word_by_word_action(btns, "Hear again", selected, self.word_pos) def add_new_word_by_word_action(self, btns, name, word, word_pos): """Adds a new word by word action. Args: btns: The buttons to add. name: The (plugin-)name of the buttons. word: The word for which these buttons are. word_pos: The word position. """ if not self.show_empty_buttons and len(btns) == 0: return if self.word_pos != word_pos: print("old item", word, word_pos, self.word_pos) return group_item = QListWidgetItem() group_item.setFlags(Qt.ItemIsSelectable) label = QLabel(name) label.setFixedSize(self.word_by_word_actions.width() - 15, 30) label.setContentsMargins(5, 0, 0, 0) label.setWordWrap(True) group_item.setSizeHint(label.size()) self.word_by_word_actions.addItem(group_item) self.word_by_word_actions.setItemWidget(group_item, label) for btn in btns: btn.setFixedSize(self.word_by_word_actions.width() - 15, 30) item = QListWidgetItem() item.setSizeHint(btn.size()) item.setFlags(Qt.ItemIsSelectable) self.word_by_word_actions.addItem(item) self.word_by_word_actions.setItemWidget(item, btn) def find_meta_data(self, word): """Gets all the meta_data for the given word. Args: word: The word for which the meta_data should be found. Returns: The meta_data """ meta_data_with_word = [] for m_d in self.transcription_meta_data: if m_d.get(c.WORD) == word.lower(): meta_data_with_word.append(m_d) return meta_data_with_word def replace_selection(self, new_word): """Replace the selection with the given word Args: new_word: The replacement. """ cursor = self.text.textCursor() old_cursor_pos = cursor.position() cursor.insertText(new_word) cursor.setPosition(old_cursor_pos, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.MoveAnchor) self.text.setTextCursor(cursor) self.word_by_word_actions.clear() def get_selection(self): """Returns the current selection Returns: The current selection. """ return self.text.textCursor().selectedText() def get_text(self): """Returns the current text Returns: The current text. """ return self.text.toPlainText() def set_text(self, new_text, restore_line_breaks=False): """Replace the text with the new text. Args: new_text: The new text. restore_line_breaks: If true, tries to restore the line breaks. (Default value = False) """ cursor = self.text.textCursor() old_cursor_pos = cursor.position() if restore_line_breaks: self.set_text_with_line_breaks(new_text) else: self.text.setPlainText(new_text) cursor.setPosition(old_cursor_pos, QTextCursor.MoveAnchor) self.text.setTextCursor(cursor) def get_word_at(self, pos): """Returns the word at the given position. Args: pos: The position of the word. Returns: The word at the given position. """ text = self.text.toPlainText().strip().split() if pos < 0 or pos > len(text): return None return text[pos % len(text)] def set_word_at(self, word, pos, replace_old): """Sets the word at the given position. Args: word: The replacement. pos: The position. replace_old: If true, the old word at the position will be replaced, otherwise the word will be set before the old word. """ old_word = self.get_word_at(pos) cursor = self.text.textCursor() cursor_pos = cursor.position() if pos < 0: self.text.setPlainText(word + " " + self.text.toPlainText()) cursor.setPosition(cursor_pos, QTextCursor.MoveAnchor) self.text.setTextCursor(cursor) return text = self.text.toPlainText().strip().split() if replace_old and pos < len(text): if word: text[pos] = word else: text.pop(pos) else: text.insert(pos, word) text = " ".join(text) self.set_text_with_line_breaks(text) cursor_pos += len(word) if replace_old: cursor_pos -= len(old_word) if not word: cursor_pos -= 1 else: cursor_pos += 1 words_to_cursor_pos = self.text.toPlainText()[:cursor_pos].split() self.word_pos = len(words_to_cursor_pos) - 1 cursor.setPosition(cursor_pos, QTextCursor.MoveAnchor) cursor.movePosition(QTextCursor.StartOfWord, QTextCursor.MoveAnchor) self.text.setTextCursor(cursor) def find_line_breaks(self): """Returns the lien breaks in the text. Returns: The positions of the linebreaks """ found = [] start = 0 text = self.text.toPlainText() while True: start = text.find("\n", start) if start == -1: return found found.append(start) start += len("\n") def set_text_with_line_breaks(self, text): """Sets the text with linebreaks. Args: text: the new text. """ line_breaks = self.find_line_breaks() for n in line_breaks: text = text[:n + 1] + "\n" + text[n + 1:] text = text.replace(" \n", "\n") text = text.replace("\n ", "\n") self.text.setPlainText(text) def insert_time_stamp(self): """Inserts the current timestamp at the current cursor position.""" cursor = self.text.textCursor() time = "[" + convert_ms(self.media_player.position()) + "]" cursor.insertText(time) def start_hear_again(self, start_time, end_time): """Starts the audio for the specific word from the hear again button. Args: start_time: When to start the audio. end_time: When to end the audio. """ if self.media_player.state() == QMediaPlayer.PlayingState: return self.media_player.pause() self.word_start_time = start_time self.word_end_time = end_time self.media_player.setPosition(self.word_start_time) self.on_play()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pbPlay.clicked.connect(self.lectureClicked) self.ui.pbPause.clicked.connect(self.pauseClicked) self.ui.pbStop.clicked.connect(self.stopClicked) self.ui.pbNext.clicked.connect(self.nextClicked) self.ui.pbPrevious.clicked.connect(self.previousClicked) self.ui.pbAdd.clicked.connect(self.addClicked) self.ui.pbDelete.clicked.connect(self.deleteClicked) self.ui.dVolume.valueChanged.connect(self.volume) self.mediaPlayer = QMediaPlayer() self.mediaPlayer.setVideoOutput(self.ui.wLecteur) self.mediaPlayer.durationChanged.connect(self.mediaDurationCnahged) self.mediaPlayer.positionChanged.connect(self.mediaPositionCnahged) self.ui.wList.itemDoubleClicked.connect(self.mediaSelected) mediaContent = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi")) self.mediaPlayer.setMedia(mediaContent) def lectureClicked(self): print("Play") self.mediaPlayer.play() def pauseClicked(self): print("Pause") if self.mediaPlayer.state() == QMediaPlayer.PausedState: self.mediaPlayer.play() else: self.mediaPlayer.pause() def stopClicked(self): print("Stop") self.mediaPlayer.stop() def nextClicked(self): print("Next") self.mediaPlayer.next() def previousClicked(self): print("Previous") self.mediaPlayer.previous() def volume(self): valeurVolume = self.ui.dVolume.value() self.mediaPlayer.setVolume(valeurVolume) self.ui.lPourcent.setText(str(valeurVolume) + "%") def mediaDurationCnahged(self): print("mediaLoaded") self.ui.lTemps.setText("00:00:00") #12 mediaDuration = self.mediaPlayer.duration( ) #donne le temps en milisecondes self.ui.sTimeLine.setRange(0, mediaDuration) #12 totalTimeMedia = QTime(0, 0, 0) totalTimeMedia = totalTimeMedia.addMSecs( mediaDuration) #convertir de milisecondes en H:m:s self.ui.lTempsTotal.setText(totalTimeMedia.toString("HH:mm:ss")) def mediaPositionCnahged(self): mediaPosition = self.mediaPlayer.position() self.ui.sTimeLine.setValue(mediaPosition) #12 currentTimeMedia = QTime(0, 0, 0) currentTimeMedia = currentTimeMedia.addMSecs(mediaPosition) self.ui.lTemps.setText(currentTimeMedia.toString("HH:mm:ss")) def mediaSelected(self): currentItem = self.ui.wList.currentItem() mediaContent = QMediaContent(QUrl.fromLocalFile((currentItem.text()))) self.mediaPlayer.setMedia(mediaContent) self.lectureClicked() def addClicked(self): print("+") nomMedia = QFileDialog.getOpenFileName( self, "Choix Film", "C:/Users/AELION/Desktop/Aelion/PyCharm/VideoProject", "Movie files (*.avi *.mp4)") # item = QListWidgetItem(nomMedia[0]) # self.ui.wList.addItem(item) fInfo = QFileInfo(nomMedia[0]) fShortName = fInfo.baseName() item = QListWidgetItem(fShortName) item.setToolTip(nomMedia[0]) self.ui.wList.addItem(item) def deleteClicked(self): print("-") rowItem = self.ui.wList.currentRow() if rowItem != -1: self.ui.wList.takeItem(rowItem)
class Die(QWidget): def __init__(self): super().__init__() self.width = 75 self.height = self.width self.x = 0 self.y = 0 self.board_tile_width = 0 self.board_tile_height = self.board_tile_width self.sides = 6 self.dice_initialized = False self.draw_dice = False self.dice_amount = 0 self.audio_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.audio_player.setMedia( QUrl.fromLocalFile( definitions.ROOT_DIR + "/Trivial_Purfuit/resources/audio/dice_roll.mp3")) self.audio_player.setVolume(50) self.image_path = definitions.ROOT_DIR + "/Trivial_Purfuit/src/die/" def roll(self): self.audio_player.play() self.dice_amount = 1 + random.randrange(self.sides) return self.dice_amount def paintEvent(self, event): self.draw_dice_fun() # end paintEvent() def draw_dice_fun(self): painter = QPainter(self) self.x = self.board_tile_width * 6 self.y = self.board_tile_height * 2 # initial dice painter.drawImage(QRect(self.x, self.y, self.width, self.height), QImage(self.image_path + "dice-six-faces-six.png")) if not self.dice_initialized: self.x = self.board_tile_width * 5 - self.width self.y = self.board_tile_height * 5 - self.height self.dice_initialized = True elif self.dice_amount == 1: painter.drawImage( QRect(self.x, self.y, self.width, self.height), QImage(self.image_path + "dice-six-faces-one.png")) elif self.dice_amount == 2: painter.drawImage( QRect(self.x, self.y, self.width, self.height), QImage(self.image_path + "dice-six-faces-two.png")) elif self.dice_amount == 3: painter.drawImage( QRect(self.x, self.y, self.width, self.height), QImage(self.image_path + "dice-six-faces-three.png")) elif self.dice_amount == 4: painter.drawImage( QRect(self.x, self.y, self.width, self.height), QImage(self.image_path + "dice-six-faces-four.png")) elif self.dice_amount == 5: painter.drawImage( QRect(self.x, self.y, self.width, self.height), QImage(self.image_path + "dice-six-faces-five.png")) elif self.dice_amount == 6: painter.drawImage( QRect(self.x, self.y, self.width, self.height), QImage(self.image_path + "dice-six-faces-six.png")) # end if self.draw_dice = False
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow( ) # on veut utiliser qu'il y a dans le fichier généré self.ui.setupUi( self) # on charge tous les composants graphiques qui sont dedans self.mediaPlayer = QMediaPlayer() self.mediaPlayer.setVideoOutput(self.ui.videoWidget) self.ui.dial.setValue(50) # pour avoir le son à 50% de base self.mediaPlayer.setVolume(self.ui.dial.value()) self.ui.volume.setText(f"{self.ui.dial.value()}%") self.ui.pbLecture.clicked.connect(self.lectureClicked) self.ui.pbPause.clicked.connect(self.pauseClicked) self.ui.pbStop.clicked.connect(self.stopClicked) self.ui.dial.valueChanged.connect(self.displayVolume) self.mediaPlayer.durationChanged.connect(self.mediaDurationChanged) self.mediaPlayer.positionChanged.connect(self.mediaPositionChanged) self.ui.sTempsCourant.valueChanged.connect(self.sliderPositionChanged) self.ui.pbAjouter.clicked.connect(self.ajouterMedia2) self.ui.pbSupprimer.clicked.connect(self.supprMedia) self.ui.listeLecture.itemDoubleClicked.connect(self.mediaSelected2) self.ui.pbPrec.clicked.connect(self.precClicked) self.ui.pbSuiv.clicked.connect(self.suivClicked) # mediaContent = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi")) # self.mediaPlayer.setMedia(mediaContent) def lectureClicked(self): print("Lecture !") self.mediaPlayer.play() def pauseClicked(self): print("Pause !") self.mediaPlayer.pause() def stopClicked(self): print("Stop !") self.mediaPlayer.stop() totalTimeMedia = QTime(0, 0, 0) self.ui.lTempsTotal.setText(totalTimeMedia.toString("HH:mm:ss")) def displayVolume(self): self.mediaPlayer.setVolume(self.ui.dial.value()) self.ui.volume.setText(f"{self.ui.dial.value()}%") print(f"Volume modifié à {self.ui.dial.value()}%") def mediaDurationChanged(self): print("mediaLoaded") self.ui.lTempsCourant.setText("00:00:00") mediaDuration = self.mediaPlayer.duration() self.ui.sTempsCourant.setRange(0, mediaDuration) ########## totalTimeMedia = QTime(0, 0, 0) totalTimeMedia = totalTimeMedia.addMSecs(mediaDuration) self.ui.lTempsTotal.setText(totalTimeMedia.toString("HH:mm:ss")) def mediaPositionChanged(self): self.ui.sTempsCourant.valueChanged.disconnect( self.sliderPositionChanged) mediaPosition = self.mediaPlayer.position() self.ui.sTempsCourant.setValue(mediaPosition) ########### currentTimeMedia = QTime(0, 0, 0) currentTimeMedia = currentTimeMedia.addMSecs(mediaPosition) self.ui.lTempsCourant.setText(currentTimeMedia.toString("HH:mm:ss")) self.ui.sTempsCourant.valueChanged.connect(self.sliderPositionChanged) def sliderPositionChanged(self): # comment ça marche ??? self.mediaPlayer.positionChanged.disconnect(self.mediaPositionChanged) self.mediaPlayer.setPosition(self.ui.sTempsCourant.value()) self.mediaPlayer.positionChanged.connect(self.mediaPositionChanged) def ajouterMedia(self): nomMedia = QFileDialog.getOpenFileName(self, "Choix Film", "c:/", "Movie Files (*.mp4 *.avi)") item = QListWidgetItem(nomMedia[0]) self.ui.listeLecture.addItem(item) print("Média ajouté !") def ajouterMedia2(self): nomMedia = QFileDialog.getOpenFileName(self, "Choix Film", "c:/", "Movie Files (*.avi *.mp4)") if nomMedia[ 0] == "": #si aucun fichier selectionné (si "Annuler" est sélectionné) return # return + vide => sortie de la fonction fInfo = QFileInfo(nomMedia[0]) fShortName = fInfo.baseName() item = QListWidgetItem(fShortName) item.setToolTip(nomMedia[0]) self.ui.listeLecture.addItem(item) def supprMedia(self): rowItem = self.ui.listeLecture.currentRow() if rowItem != -1: self.ui.listeLecture.takeItem(rowItem) print("Média supprimé !") self.stopClicked() def mediaSelected(self): currentItem = self.ui.listeLecture.currentItem() mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.text())) self.mediaPlayer.setMedia(mediaContent) self.lectureClicked() print("Média sélectionné !") def mediaSelected2(self): currentItem = self.ui.listeLecture.currentItem() mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.toolTip())) self.mediaPlayer.setMedia(mediaContent) self.lectureClicked() def suivClicked(self): currentItemRow = self.ui.listeLecture.currentRow() if currentItemRow == -1: return totalItems = self.ui.listeLecture.count() self.ui.listeLecture.setCurrentRow((currentItemRow + 1) % totalItems) print("Morceau suivant !") self.mediaSelected2() def precClicked(self): currentItemRow = self.ui.listeLecture.currentRow() if currentItemRow == -1: return totalItems = self.ui.listeLecture.count() self.ui.listeLecture.setCurrentRow((currentItemRow - 1) % totalItems) print("Morceau précédent !") self.mediaSelected2()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() # Create widgets self.ui = Ui_MainWindow() self.ui.setupUi(self) self.mediaPlayer = QMediaPlayer() self.playlist = QMediaPlaylist() #mediaContent1 = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi")) #mediaContent2=QMediaContent(QUrl.fromLocalFile("Doom.Patrol1.mp4")) #self.playlist.addMedia(mediaContent1) #self.playlist.addMedia(mediaContent2) #self.playlist.setCurrentIndex(1) #self.mediaPlayer.setMedia(self.playlist) self.mediaPlayer.setVideoOutput(self.ui.wvideo) self.ui.ltemps.setText("") self.ui.lduree.setText("") self.ui.dialVolume.setValue(0) self.ui.lvolume_2.setText(str(self.ui.dialVolume.value())) self.ui.pblecture.clicked.connect(self.lectureClicked) self.ui.pbpause.clicked.connect(self.pauseClicked) self.ui.pbstop.clicked.connect(self.stopClicked) self.ui.pbsuivant.clicked.connect(self.suivantClicked) self.ui.pbprecedent.clicked.connect(self.precedentClicked) self.ui.pbajouter.clicked.connect(self.ajouter2) self.ui.pbsupprimer.clicked.connect(self.supprimer) self.ui.listWidget.itemDoubleClicked.connect(self.mediaSelected2) self.ui.dialVolume.valueChanged.connect(self.volumeChanged) #self.mediaPlayer.positionChanged.connect(self.tempsChanged) self.mediaPlayer.positionChanged.connect(self.lectureEnCours) #self.mediaPlayer.positionChanged.connect(self.progressionChanged) self.ui.stpscourant.sliderMoved.connect(self.sliderMove) def sliderMove(self): self.mediaPlayer.setPosition(self.ui.stpscourant.value()) def lectureEnCours(self): mediaPosition = self.mediaPlayer.position() currentTimeMedia = QTime(0, 0, 0) currentTimeMedia = currentTimeMedia.addMSecs(mediaPosition) mediaDuration = self.mediaPlayer.duration() totalTimeMedia = QTime(0, 0, 0) totalTimeMedia = totalTimeMedia.addMSecs(mediaDuration) self.ui.ltemps.setText(currentTimeMedia.toString("HH:mm:ss")) self.ui.lduree.setText(totalTimeMedia.toString("HH:mm:ss")) self.ui.stpscourant.setRange(0, self.mediaPlayer.duration()) self.ui.stpscourant.setValue(self.mediaPlayer.position()) def lectureClicked(self): print("Lecture!!") self.mediaPlayer.play() def pauseClicked(self): print("pause!!") if self.mediaPlayer.state() == QMediaPlayer.PausedState: self.mediaPlayer.play() else: self.mediaPlayer.pause() def stopClicked(self): print("stop!!") self.mediaPlayer.stop() def suivantClicked(self): print("suivant!!") currentItemRow = self.ui.listWidget.currentRow() if currentItemRow == -1: return totalItems = self.ui.listWidget.count() self.ui.listWidget.setCurrentRow((currentItemRow + 1) % totalItems) self.mediaSelected2() def precedentClicked(self): print("precedent!!") currentItemRow = self.ui.listWidget.currentRow() if currentItemRow == -1: return totalItems = self.ui.listWidget.count() self.ui.listWidget.setCurrentRow((currentItemRow - 1) % totalItems) self.mediaSelected2() def volumeChanged(self): self.ui.dialVolume.setMaximum(100) self.mediaPlayer.setVolume(self.ui.dialVolume.value()) self.ui.lvolume_2.setText(str(self.ui.dialVolume.value())) def ajouter(self): nomMedia = QFileDialog.getOpenFileName( self, "Choix Film", "C:/Users/AELION/PycharmProjects/videoLHector", "Movie Files (*.avi *.mp4)") item = QListWidgetItem(nomMedia[0]) self.ui.listWidget.addItem(item) def ajouter2(self): nomMedia = QFileDialog.getOpenFileName( self, "Choix Film", "C:/Users/AELION/PycharmProjects/videoLHector", "Movie Files (*.avi *.mp4)") fInfo = QFileInfo(nomMedia[0]) fShortName = fInfo.baseName() print(fShortName) item = QListWidgetItem(fShortName) item.setToolTip(nomMedia[0]) self.ui.listWidget.addItem(item) def supprimer(self): rowItem = self.ui.listWidget.currentRow() if rowItem != -1: self.ui.listWidget.takeItem(rowItem) def mediaSelected1(self): currentItem = self.ui.listWidget.currentItem() mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.text())) self.mediaPlayer.setMedia(mediaContent) self.lectureClicked() def mediaSelected2(self): currentItem = self.ui.listWidget.currentItem() mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.toolTip())) self.mediaPlayer.setMedia(mediaContent) self.lectureClicked()
class VideoPlaybackDevice(Filter): playbackStarted = Signal() playbackPaused = Signal() sequenceOpened = Signal(str, QDateTime, QDateTime, list) currentTimestampChanged = Signal(QDateTime) def __init__(self, environment): super().__init__(False, False, environment) self.video_out = OutputPort(False, "video", environment) self.audio_out = OutputPort(False, "audio", environment) self.addStaticPort(self.video_out) self.addStaticPort(self.audio_out) self.filename = self.propertyCollection().defineProperty( "filename", "", "avi file name") def newDuration(self, newDuration): logger.debug("newDuration %s", newDuration) self.sequenceOpened.emit(self.filename, QDateTime.fromMSecsSinceEpoch(0), QDateTime.fromMSecsSinceEpoch(newDuration), ["video"]) def currentMediaChanged(self, media): logger.debug("currentMediaChanged videoAv=%s audioAv=%s", self.player.isVideoAvailable(), self.player.isAudioAvailable()) def _openVideo(self): logger.debug("entering _openVideo") self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.videoOutput = DummyVideoSurface(self.player) #self.videoOutput = QVideoWidget() #self.videoOutput.show() self.player.setVideoOutput(self.videoOutput) #self.player.setMuted(True) self.player.durationChanged.connect(self.newDuration) self.player.currentMediaChanged.connect(self.currentMediaChanged) self.player.setMedia(QUrl.fromLocalFile(self.filename)) logger.debug("leaving _openVideo; videoAv=%s audioAv=%s", self.player.isVideoAvailable(), self.player.isAudioAvailable()) def _closeVideo(self): try: del self.player del self.playlist except: pass def onStart(self): ctrlSrv = Services.getService("PlaybackControl") ctrlSrv.setupConnections(self) self.playbackPaused.emit() if self.filename != "": self._openVideo() def onStop(self): ctrlSrv = Services.getService("PlaybackControl") ctrlSrv.removeConnections(self) self._closeVideo() @Slot() def startPlayback(self): self.player.play() self.playbackStarted.emit() logger.debug("leaving startPlayback; videoAv=%s audioAv=%s", self.player.isVideoAvailable(), self.player.isAudioAvailable()) @Slot() def pausePlayback(self): self.player.pause() self.playbackPaused.emit() def newDataEvent(self): t = time.monotonic() if self.lastSendTime is not None: if t - self.lastSendTime < self.timeout_ms * 1e-3: # we are still earlier than the requested framerate return self.lastSendTime = t self.counter += 1 c = "Sample %d" % self.counter s = DataSample(c.encode("utf8"), "text/utf8", int(time.time() / DataSample.TIMESTAMP_RES)) logging.getLogger(__name__).info("transmit: %s", c) self.beforeTransmit(s) self.outPort.transmit(s) self.afterTransmit() def stepForward(self): pass def stepBackward(self): pass def seekBeginning(self): pass def seekEnd(self): pass def seekTime(self, timestamp): pass def setSequence(self, filename): self.filename def setTimeFactor(self, factor): pass
class Sound: """Loads a sound from the specified URL. Supports whatever audio formats that PySide2 supports (depending on locally-installed codecs). No error is raised if the file isn't found or is of an unsupported format. Sounds are tracked :param url: the URL to load the sound from, can be a local file """ def __init__(self, url): # type: (str) -> None self.__url = url # Only used for debugging # Tell the app not to quit while this sound is loading, since it is plausible that a user is using sounds # without using a frame or any timers: TheApp.add_tracked(self) self.__player = QMediaPlayer(TheApp, flags=QMediaPlayer.LowLatency) self.__player.setAudioRole(QAudio.GameRole) self.__player.mediaStatusChanged.connect(self.__on_status_changed) self.__player.error.connect(self.__on_status_changed) req = request(url) content = QMediaContent(req) self.__player.setMedia(content) self.__sound_loaded = False self.__play_requested = False def __on_status_changed(self, _): # type: (QMediaPlayer.MediaStatus) -> None """Checks if the sound is loaded. If the sound has loaded without error, and the user has already told it to start playing, this will start the sound playing. If there was any failure in loading the sound, this is recorded, and the sound will never be able to be played. TheApp will also be notified that it can close if this sound is all it is waiting for. This event is also triggered by other status changes. The only other one that matters is the EndOfMedia status. In this case, TheApp is also told that it can close. :param _: (unused) media status object """ error = self.__player.error() status = self.__player.mediaStatus() if status < QMediaPlayer.LoadedMedia: return if error == QMediaPlayer.NoError and QMediaPlayer.LoadedMedia <= status < QMediaPlayer.InvalidMedia: # Check if the media is actually an audio file that is playable if self.__player.isAudioAvailable(): self.__sound_loaded = True if self.__play_requested and status != QMediaPlayer.EndOfMedia: # Play and don't do anything else now self.play() return else: self.__sound_loaded = False self.__play_requested = False TheApp.remove_tracked(self) def play(self): """Starts playing a sound, or restarts playing it at the point it was paused.""" if self.__sound_loaded: self.__player.play() TheApp.add_tracked(self) self.__play_requested = True def pause(self): """Stops the playing of the sound. Playing can be restarted at the stopped point with :meth:`play`.""" if self.__sound_loaded: self.__player.pause() TheApp.remove_tracked(self) self.__play_requested = False def rewind(self): """Stops playing the sound, makes it so the next :meth:`play` will start playing the sound at the beginning.""" if self.__sound_loaded: self.__player.stop() TheApp.remove_tracked(self) self.__play_requested = False def set_volume(self, volume): # type: (float) -> None """Changes the volume for the sound to be the given level on a 0 (silent) – 1.0 (maximum) scale. Default is 1. :param volume: the volume to set """ assert 0.0 <= volume <= 1.0, "volume must be given in range 0-1 inclusive" self.__player.setVolume(int(100 * volume))
import sys import PySide2 from PySide2.QtCore import QUrl from PySide2.QtWidgets import QApplication from PySide2.QtMultimedia import QMediaPlayer from PySide2.QtMultimediaWidgets import QVideoWidget if __name__ == '__main__': DATA_DIR = 'C:/Users/Noah/Documents/se_data' VIDEO_PATH = DATA_DIR + '/videos/Thundercats/sword_in_a_hole.avi' app = QApplication(sys.argv) video = QVideoWidget() player = QMediaPlayer() player.setMedia(QUrl.fromLocalFile(VIDEO_PATH)) player.setVideoOutput(video) def video_available_changed(available): if available: video.updateGeometry() video.adjustSize() player.mediaStatusChanged.connect(video_available_changed) video.show() player.play() app.exec_() player.stop()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pblecture.clicked.connect(self.lectureClicked) self.ui.pbpause.clicked.connect(self.pauseClicked) self.ui.pbstop.clicked.connect(self.stopClicked) self.ui.pbmoins.clicked.connect(self.supprMedia) self.ui.pbplus.clicked.connect(self.ajouterMedia) self.ui.pbprecedent.clicked.connect(self.precedentClicked) self.ui.pbsuivant.clicked.connect(self.suivantClicked) self.mediaPlayer = QMediaPlayer() #creation de la variable mediaPlayer self.mediaPlayer.setVideoOutput( self.ui.ecran) #on projette la var mediaPlayer sur ecran. self.ui.dialVolume.valueChanged.connect(self.volumeChanged) self.mediaPlayer.durationChanged.connect(self.mediaDurationChanged) self.mediaPlayer.positionChanged.connect(self.mediaPositionChanged) self.ui.listWidget.itemDoubleClicked.connect(self.mediaSelected) # Commande qui permet de lancer le film (depuis le début) mediaContent = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi")) self.mediaPlayer.setMedia(mediaContent) #def slideChanged(self): # self.mediaPlayer.position() # self.ui.timeline.setValue() def ajouterMedia(self): nomMedia = QFileDialog.getOpenFileName( self, "ChoixFilm", "c:/Users/AELION/PycharmProjects/lect_video", "(*.avi *.mp4)") fInfo = QFileInfo(nomMedia[0]) fShortName = fInfo.baseName() item = QListWidgetItem(fShortName) item.setToolTip(nomMedia[0]) self.ui.listWidget.addItem(item) def suivantClicked(self): currentItemRow = self.ui.listWidget.currentRow() if currentItemRow == -1: return totalItems = self.ui.listWidget.count() self.ui.listWidget.setCurrentRow((currentItemRow + 1) % totalItems) self.mediaSelected() def precedentClicked(self): currentItemRow = self.ui.listWidget.currentRow() if currentItemRow == -1: return totalItems = self.ui.listWidget.count() self.ui.listWidget.setCurrentRow((currentItemRow - 1) % totalItems) self.mediaSelected() def supprMedia(self): rowItem = self.ui.listWidget.currentRow() if rowItem != -1: #au cas ou on appuie sur Supp et qu'il n'y a pas d'objet self.ui.listWidget.takeItem(rowItem) def mediaSelected(self): currentItem = self.ui.listWidget.currentItem() mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.toolTip())) self.mediaPlayer.setMedia(mediaContent) self.lectureClicked() def mediaDurationChanged(self): self.ui.debut.setText("00:00:00") mediaDuration = self.mediaPlayer.duration( ) #recoit le temps total en Millisec self.ui.timeline.setRange( 0, mediaDuration ) #découpe le timeline proportionnelement au temps en millisec totalTimeMedia = QTime(0, 0, 0) totalTimeMedia = totalTimeMedia.addMSecs( mediaDuration) #convertit le temps total en h:m:s self.ui.fin.setText(totalTimeMedia.toString("HH:mm:ss")) def mediaPositionChanged(self): mediaPosition = self.mediaPlayer.position() self.ui.timeline.setValue(mediaPosition) currentTimeMedia = QTime( 0, 0, 0, ) currentTimeMedia = currentTimeMedia.addMSecs(mediaPosition) self.ui.debut.setText(currentTimeMedia.toString("HH:mm:ss")) def volumeChanged(self): self.mediaPlayer.setVolume(self.ui.dialVolume.value()) self.ui.labelVol.setText(str(self.ui.dialVolume.value()) + "%") def lectureClicked(self): print("Lecture!!") self.mediaPlayer.play() def pauseClicked(self): print("Pause !!") if self.mediaPlayer.state() == QMediaPlayer.PausedState: self.mediaPlayer.play() elif self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() def stopClicked(self): print("Stop!!") self.mediaPlayer.stop()
class Board(QMainWindow, board_funcs): """ Description ------------- The board for Trivial Purfuit. TODO: JGC - Merge the common stuff between board_funcs and this class. There's duplicate code, but you did everything in this class first. """ def __init__(self): super().__init__() self.setWindowTitle("Trivial Purfuit Board") self.num_row_tiles = 9 self.num_col_tiles = 9 self.board_tile_width = 95 self.board_tile_height = self.board_tile_width self.board_width = self.num_row_tiles * self.board_tile_width self.board_height = self.num_col_tiles * self.board_tile_height monitor = QApplication.desktop().geometry() self.resize(monitor.width(), self.board_height) #default is event self.qtype1_tile_color = Qt.white #default is holidau self.qtype2_tile_color = Qt.green #default is location self.qtype3_tile_color = Qt.blue #default is people self.qtype4_tile_color = Qt.red self.roll_again_tile_color = Qt.darkGray self.players_initialized = False self.dice_initialized = False # Background music playlist self.playlist = QMediaPlaylist() self.playlist.addMedia( QUrl.fromLocalFile( definitions.ROOT_DIR + "/Trivial_Purfuit/resources/audio/sea_change.mp3")) self.playlist.addMedia( QUrl.fromLocalFile(definitions.ROOT_DIR + "/Trivial_Purfuit/resources/audio/feblu.mp3")) self.playlist.addMedia( QUrl.fromLocalFile( definitions.ROOT_DIR + "/Trivial_Purfuit/resources/audio/vals_de_rodrigues.mp3")) self.playlist.addMedia( QUrl.fromLocalFile( definitions.ROOT_DIR + "/Trivial_Purfuit/resources/audio/escaping_time.mp3")) self.playlist.setPlaybackMode(QMediaPlaylist.Loop) self.playlist_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.playlist_player.setPlaylist(self.playlist) self.number_of_players = 0 self.player_list = [] self.die = Die() self.board_menu = BoardMenu() self.qa_manager = QuestionManager( definitions.ROOT_DIR + "/Trivial_Purfuit/csvs/questions-and-answers.csv") self.question_categories = [ definitions.question_type1, definitions.question_type2, definitions.question_type3, definitions.question_type4 ] self.image_path = definitions.ROOT_DIR + "/Trivial_Purfuit/src/board/images/" self.restart_menu = RestartMenu() # end __init__() def initialize_game(self): """ Description ------------- - TODO: JGC """ monitor = QApplication.desktop().geometry() # Navigation Menu setup self.board_menu.resize(monitor.width(), monitor.height()) self.board_menu.ui.player_order_group_box.move( self.board_width, self.board_menu.ui.player_order_group_box.y()) self.board_menu.ui.navigation_group.move(self.board_width, monitor.height() / 3) temp_x = self.board_menu.ui.navigation_group.x() temp_y = self.board_menu.ui.navigation_group.y( ) + self.board_menu.ui.navigation_group.height() self.board_menu.ui.misc_group.move(temp_x, temp_y) self.board_menu.ui.audio_group.move( self.board_menu.ui.misc_group.x(), self.board_menu.ui.misc_group.y() + self.board_menu.ui.misc_group.height()) # Connect signals/slots for buttons on board menu self.connect(self.board_menu.ui.up_button, SIGNAL("clicked()"), partial(self.start_move, "UP")) self.connect(self.board_menu.ui.down_button, SIGNAL("clicked()"), partial(self.start_move, "DOWN")) self.connect(self.board_menu.ui.left_button, SIGNAL("clicked()"), partial(self.start_move, "LEFT")) self.connect(self.board_menu.ui.right_button, SIGNAL("clicked()"), partial(self.start_move, "RIGHT")) self.connect(self.board_menu.ui.reset_button, SIGNAL("clicked()"), self.cheat) self.connect(self.board_menu.ui.roll_die_button, SIGNAL("clicked()"), self.get_dice_value) # Connect signals/slots for audio slider widgets on board menu self.connect(self.board_menu.ui.music_volume_slider, SIGNAL("sliderReleased()"), self.update_music_volume) self.connect(self.board_menu.ui.sound_effects_volume, SIGNAL("sliderReleased()"), self.update_sound_effect_volume) self.board_menu.ui.sound_effects_volume.setValue(50) self.board_menu.ui.music_volume_slider.setValue(50) # Die Setup/initialization self.initialize_dice() # Game sounds self.win_noise = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.lose_noise = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.win_noise.setMedia( QUrl.fromLocalFile( definitions.ROOT_DIR + "/Trivial_Purfuit/resources/audio/win_bing.mp3")) self.lose_noise.setMedia( QUrl.fromLocalFile( definitions.ROOT_DIR + "/Trivial_Purfuit/resources/audio/lose_noise.mp3")) # Start the background music self.playlist_player.play() self.layout().addChildWidget(self.die) self.layout().addChildWidget(self.board_menu) self.player_list = self.set_round_order(self.player_list) self.current_player = self.player_list[0] self.current_player_list_index = 0 self.current_player.is_current_player = True self.board_menu.ui.current_player_field.insertPlainText( str(self.current_player.name)) # end initialize_game() def hide_dirs(self): self.board_menu.ui.down_button.setVisible(False) self.board_menu.ui.up_button.setVisible(False) self.board_menu.ui.left_button.setVisible(False) self.board_menu.ui.right_button.setVisible(False) #end hide_dirs def avail_dirs(self): """ Determines possible directions the player could move based on current location Input: The player token who is currently moving Output: List of available directions """ player_row = self.current_player.location[0] player_col = self.current_player.location[1] directions = list() if self.get_tile_type(player_row + 1, player_col) != "Invalid": directions.append("Down") if self.get_tile_type(player_row - 1, player_col) != "Invalid": directions.append("Up") if self.get_tile_type(player_row, player_col - 1) != "Invalid": directions.append("Left") if self.get_tile_type(player_row, player_col + 1) != "Invalid": directions.append("Right") return directions def update_dirs(self): """ Hides the movement buttons based on whether or not its a valid move Input: Output: """ player_row = self.current_player.location[0] player_col = self.current_player.location[1] self.board_menu.ui.down_button.setVisible(True) self.board_menu.ui.up_button.setVisible(True) self.board_menu.ui.left_button.setVisible(True) self.board_menu.ui.right_button.setVisible(True) if self.get_tile_type(player_row + 1, player_col) == "Invalid" \ or self.current_player.direction_to_move == "UP": self.board_menu.ui.down_button.setVisible(False) if self.get_tile_type(player_row - 1, player_col) == "Invalid" \ or self.current_player.direction_to_move == "DOWN": self.board_menu.ui.up_button.setVisible(False) if self.get_tile_type(player_row, player_col - 1) == "Invalid" \ or self.current_player.direction_to_move == "RIGHT": self.board_menu.ui.left_button.setVisible(False) if self.get_tile_type(player_row, player_col + 1) == "Invalid" \ or self.current_player.direction_to_move == "LEFT": self.board_menu.ui.right_button.setVisible(False) # end update_dirs() def set_default_game_volume(self): self.playlist_player.setVolume(50) self.board_menu.ui.music_volume_slider.setValue(50) self.board_menu.ui.music_volume_slider.setValue(50) # end set_default_game_volume def update_music_volume(self): tmp_volume = self.board_menu.ui.music_volume_slider.value() self.playlist_player.setVolume(tmp_volume) # end update_music_volume() def update_sound_effect_volume(self): tmp_volume = self.board_menu.ui.sound_effects_volume.value() # Set volume for lose/win effects self.win_noise.setVolume(tmp_volume) self.lose_noise.setVolume(tmp_volume) # Set the volume for each player token for player in self.player_list: player.audio_player.setVolume(tmp_volume) # Set the die volume self.die.audio_player.setVolume(tmp_volume) # end update_sound_effect_volume() def get_dice_value(self): """ Description ------------- - TODO: JGC """ self.current_player.moves_left = self.die.roll() self.current_player.direction_to_move = "NONE" self.board_menu.ui.dice_field.clear() self.board_menu.ui.dice_field.insertPlainText( str(self.current_player.moves_left)) self.board_menu.ui.current_player_field.clear() self.board_menu.ui.current_player_field.insertPlainText( str(self.current_player.name)) self.update_dirs() self.board_menu.ui.roll_die_button.setVisible(False) if self.current_player.moves_left == 6: self.current_player.moves_left = 0 self.hide_dirs() self.board_menu.ui.roll_die_button.setVisible(True) answer, valid_input = QInputDialog().getItem( self, "Select Cake Headquarters", "Select:", self.question_categories, 0, False) if answer == self.question_categories[0]: self.current_player.location[0] = 4 self.current_player.location[1] = 8 self.current_player.x = self.board_tile_width * 9 - ( self.current_player.width * self.current_player.x_offset) self.current_player.y = self.board_tile_height * 5 - ( self.current_player.height * self.current_player.y_offset) elif answer == self.question_categories[1]: self.current_player.location[0] = 8 self.current_player.location[1] = 4 self.current_player.x = self.board_tile_width * 5 - ( self.current_player.width * self.current_player.x_offset) self.current_player.y = self.board_tile_height * 9 - ( self.current_player.height * self.current_player.y_offset) elif answer == self.question_categories[2]: self.current_player.location[0] = 0 self.current_player.location[1] = 4 self.current_player.x = self.board_tile_width * 5 - ( self.current_player.width * self.current_player.x_offset) self.current_player.y = self.board_tile_height * 1 - ( self.current_player.height * self.current_player.y_offset) elif answer == self.question_categories[3]: self.current_player.location[0] = 4 self.current_player.location[1] = 0 self.current_player.x = self.board_tile_width * 1 - ( self.current_player.width * self.current_player.x_offset) self.current_player.y = self.board_tile_height * 5 - ( self.current_player.height * self.current_player.y_offset) else: print("Incorrect answer") self.current_player.turn_status = True self.current_player.draw_token = True self.current_player.update() self.perform_tile_action() self.board_menu.ui.dice_field.clear() # Updates the dice image to immediately reflect the correct image. self.die.update() # end get_dice_value() def start_move(self, label): """ Description ------------- - TODO: JGC """ try: # TODO: Could add a check to restart for those too impatient. self.current_player.audio_player.play() if (label == "UP" or label == "DOWN" or label == "LEFT" or label == "RIGHT"): while (self.current_player.moves_left > 0): self.current_player.direction_to_move = label self.current_player.turn_status = True self.current_player.update_location(direction=label) self.update_dirs() self.current_player.moves_left = self.current_player.moves_left - 1 self.board_menu.ui.dice_field.clear() self.board_menu.ui.dice_field.insertPlainText( str(self.current_player.moves_left)) if len(self.avail_dirs() ) > 2 and self.current_player.moves_left != 0: break else: if self.current_player.location == [0, 0]: if self.current_player.direction_to_move == "UP": label = "RIGHT" else: label = "DOWN" elif self.current_player.location == [0, 8]: if self.current_player.direction_to_move == "UP": label = "LEFT" else: label = "DOWN" elif self.current_player.location == [8, 0]: if self.current_player.direction_to_move == "DOWN": label = "RIGHT" else: label = "UP" elif self.current_player.location == [8, 8]: if self.current_player.direction_to_move == "DOWN": label = "LEFT" else: label = "UP" if self.current_player.moves_left == 0: self.current_player.done_moving = True # end if # Manually calls the paint QEvent. self.update() # Once the player is out of spaces to move, prompt the player with a # question from the QA Manager. if self.current_player.moves_left == 0 and self.current_player.done_moving: self.current_player.direction_to_move = "NONE" self.hide_dirs() self.board_menu.ui.roll_die_button.setVisible(True) self.current_player.done_moving = False self.perform_tile_action() # end if else: print("No moves left!") except ValueError: print("[ERROR] Invalid dice roll amount!") # end start_move() def initialize_player_tokens(self, total_players, player_one, player_two, player_three, player_four): """ Description ------------- TODO: JGC - """ if total_players >= 1: self.player_widget = PlayerToken(player_one, self.board_tile_width, self.board_tile_height, 2.6, 2.6) self.player_widget.resize(self.board_width, self.board_height) self.layout().addChildWidget(self.player_widget) self.player_list.append(self.player_widget) if total_players >= 2: player_widget_two = PlayerToken(player_two, self.board_tile_width, self.board_tile_height, 1, 1) player_widget_two.resize(self.board_width, self.board_height) self.layout().addChildWidget(player_widget_two) self.player_list.append(player_widget_two) if total_players >= 3: player_widget_three = PlayerToken(player_three, self.board_tile_width, self.board_tile_height, 2.6, 1) player_widget_three.resize(self.board_width, self.board_height) self.layout().addChildWidget(player_widget_three) self.player_list.append(player_widget_three) if total_players >= 4: player_widget_four = PlayerToken(player_four, self.board_tile_width, self.board_tile_height, 1, 2.6) player_widget_four.resize(self.board_width, self.board_height) self.layout().addChildWidget(player_widget_four) self.player_list.append(player_widget_four) # end initialize_player_tokens() def initialize_dice(self): """ Description ------------- - TODO: JGC """ self.die.board_tile_height = self.board_tile_height self.die.board_tile_width = self.board_tile_width self.die.resize(self.board_width, self.board_height) # end initialize_dice() def cheat(self): """ Description ------------- - TODO: JGC """ self.current_player.award_cake_piece(self.question_categories[0]) self.current_player.award_cake_piece(self.question_categories[1]) self.current_player.award_cake_piece(self.question_categories[2]) self.current_player.award_cake_piece(self.question_categories[3]) self.current_player.update() # end reset_player() def is_roll_again_tile(self, row, col): """ Description ------------- Checks if the current row and column position is a holiday tile. Parameters ------------- (1) row: The selected row on the board. (2) col: The selected column on the board. """ if ((row == 0 and col == 0) or (row == 0 and col == 8) or (row == 8 and col == 0) or (row == 8 and col == 8)): return True # end if # end is_roll_again_tile() def is_qtype1_tile(self, row, col): """ Description ------------- Checks if the current row and column position is a person tile. Parameters ------------- (1) row: The selected row on the board. (2) col: The selected column on the board. """ if ((row == 0 and col == 3) or (row == 0 and col == 6) or (row == 1 and col == 0) or (row == 3 and col == 4) or (row == 4 and col == 2) or (row == 4 and col == 8) or (row == 5 and col == 0) or (row == 7 and col == 4) or (row == 8 and col == 1) or (row == 8 and col == 7)): return True # end if # end is_person_tile() def is_qtype2_tile(self, row, col): """ Description ------------- Checks if the current row and column position is an event tile. Parameters ------------- (1) row: The selected row on the board. (2) col: The selected column on the board. """ if ((row == 0 and col == 2) or (row == 0 and col == 5) or (row == 2 and col == 0) or (row == 2 and col == 4) or (row == 3 and col == 8) or (row == 4 and col == 1) or (row == 4 and col == 5) or (row == 7 and col == 0) or (row == 7 and col == 8) or (row == 8 and col == 4)): return True # end if # end is_event_tile() def is_qtype3_tile(self, row, col): """ Description ------------- Checks if the current row and column position is a location/place tile. Parameters ------------- (1) row: The selected row on the board. (2) col: The selected column on the board. """ if ((row == 0 and col == 4) or (row == 1 and col == 8) or (row == 3 and col == 0) or (row == 4 and col == 3) or (row == 4 and col == 7) or (row == 6 and col == 0) or (row == 6 and col == 4) or (row == 6 and col == 8) or (row == 8 and col == 2) or (row == 8 and col == 5)): return True # end if # end is_place_tile() def is_qtype4_tile(self, row, col): """ Description ------------- Checks if the current row and column position is a holiday tile. Parameters ------------- (1) row: The selected row on the board. (2) col: The selected column on the board. """ if ((row == 0 and col == 1) or (row == 0 and col == 7) or (row == 1 and col == 4) or (row == 2 and col == 8) or (row == 4 and col == 0) or (row == 4 and col == 6) or (row == 5 and col == 4) or (row == 5 and col == 8) or (row == 8 and col == 3) or (row == 8 and col == 6)): return True # end if # end is_holiday_tile() def is_hub_tile(self, row, col): """ Description ------------- Checks if the current row and column position is the hub tile. Parameters ------------- (1) row: The selected row on the board. (2) col: The selected column on the board. """ if (row == 4 and col == 4): return True # end is_hub_tile() def is_cake_tile(self, row, col): """ Description ------------- Checks if the current row and column position is a cake tile. Parameters ------------- (1) row: The selected row on the board. (2) col: The selected column on the board. """ if ((row == 0 and col == 4) or (row == 4 and col == 0) or (row == 4 and col == 8) or (row == 8 and col == 4)): return True # end is_cake_tile() def get_tile_type(self, row, col): """ Description ------------- Utilizes previous methods for tile checking to return a string of what tile type the current row and column position is Parameters ------------- (1) row: The selected row on the board. (2) col: The selected column on the board. """ if self.is_hub_tile(row, col): return "hub" elif self.is_qtype1_tile(row, col): return self.question_categories[0] elif self.is_qtype2_tile(row, col): return self.question_categories[1] elif self.is_qtype3_tile(row, col): return self.question_categories[2] elif self.is_qtype4_tile(row, col): return self.question_categories[3] elif self.is_roll_again_tile(row, col): return "roll_again" else: return "Invalid" # end get_tile_type() def paintEvent(self, event): """ Description ------------- - Draws the board and player tokens Parameters ------------- (1) event: The event signal (QEvent.Type.Paint). """ self.draw_board() if not self.dice_initialized: self.die.update() self.dice_initialized = True # end if for player in self.player_list: self.do_player_turn(player) # end paintEvent() def do_player_turn(self, player): """ Description ------------- TODO: JGC """ if player.turn_status: player.draw_token = True player.update() player.turn_status = False # end if # end do_player_turn() def perform_tile_action(self): """ Description ------------- - TODO: JGC """ self.current_player.update() tile_type = self.get_tile_type(self.current_player.location[0], self.current_player.location[1]) roll_again = False if tile_type in self.question_categories: good_answer = self.ask_question(self.current_player, tile_type, isCake=False) if good_answer: self.win_noise.play() roll_again = True # Verify this is a "Cake" Tile before awarding cake piece. if self.is_cake_tile(self.current_player.location[0], self.current_player.location[1]): self.current_player.award_cake_piece( cake_category=tile_type) else: self.lose_noise.play() elif (tile_type == "roll_again"): self.win_noise.play() roll_again = True QMessageBox.question(self, 'Congratulations!', 'Roll Again!', QMessageBox.Ok) elif (tile_type == "hub"): # Verify the player token has all cake pieces awarded before answering the # winning question, otherwise ask random question if self.current_player.all_cake_pieces_present(): answer, valid_input = QInputDialog().getItem( self, "Select Category", "!OTHER PLAYERS! Select the winning question category:", self.question_categories, 0, False) good_answer = self.ask_question(self.current_player, answer, isCake=False) if good_answer: self.win_noise.play() QMessageBox.question(self, 'Congratulations!', 'YOU WIN!', QMessageBox.Ok) self.restart_menu.show() else: self.lose_noise.play() else: answer, valid_input = QInputDialog().getItem( self, "Select Category", "Select the question category:", self.question_categories, 0, False) good_answer = self.ask_question(self.current_player, answer, isCake=False) if good_answer: roll_again = True else: self.lose_noise.play() else: print("Invalid Tile/Question Type Received") print("Row: " + str(self.current_player.location[0])) print("Col: " + str(self.current_player.location[1])) # If not roll again tile, point to the next player in the list if not roll_again: # Deactivate the yellow outline for current player self.current_player.is_current_player = False self.current_player_list_index = (self.current_player_list_index + 1) % len(self.player_list) self.current_player = self.player_list[ self.current_player_list_index] self.current_player.is_current_player = True self.board_menu.ui.current_player_field.clear() self.board_menu.ui.current_player_field.insertPlainText( str(self.current_player.name)) self.board_menu.ui.dice_field.clear() # end if # end perform_tile_action def draw_board(self): """ Description ------------- - Paint all of the tiles for the Trivial Purfuit board Parameters ------------- (1) event: The event signal (QEvent.Type.Paint). NOTE/TODO ------------- (1) Don't be lazy and brute force.. (2) Run the current board layout by the team """ painter = QPainter(self) painter.setPen(QPen(Qt.black, 5, Qt.SolidLine)) x = 0 y = 0 # The board is drawn from left to right. for row in range(self.num_row_tiles): for col in range(self.num_col_tiles): if self.is_roll_again_tile(row, col): painter.setBrush( QBrush(self.roll_again_tile_color, Qt.SolidPattern)) painter.drawRect(x, y, self.board_tile_width, self.board_tile_height) painter.drawImage( QRect(x, y, self.board_tile_width, self.board_tile_height), QImage(self.image_path + "roll_again.png")) elif self.is_qtype1_tile(row, col): painter.setBrush( QBrush(self.qtype1_tile_color, Qt.SolidPattern)) painter.drawRect(x, y, self.board_tile_width, self.board_tile_height) if self.is_cake_tile(row, col): painter.drawImage( QRect(x, y, self.board_tile_width, self.board_tile_height), QImage(self.image_path + "collect.png")) elif self.is_qtype4_tile(row, col): painter.setBrush( QBrush(self.qtype4_tile_color, Qt.SolidPattern)) painter.drawRect(x, y, self.board_tile_width, self.board_tile_height) if self.is_cake_tile(row, col): painter.drawImage( QRect(x, y, self.board_tile_width, self.board_tile_height), QImage(self.image_path + "collect.png")) elif self.is_qtype2_tile(row, col): painter.setBrush( QBrush(self.qtype2_tile_color, Qt.SolidPattern)) painter.drawRect(x, y, self.board_tile_width, self.board_tile_height) if self.is_cake_tile(row, col): painter.drawImage( QRect(x, y, self.board_tile_width, self.board_tile_height), QImage(self.image_path + "collect.png")) elif self.is_qtype3_tile(row, col): painter.setBrush( QBrush(self.qtype3_tile_color, Qt.SolidPattern)) painter.drawRect(x, y, self.board_tile_width, self.board_tile_height) if self.is_cake_tile(row, col): painter.drawImage( QRect(x, y, self.board_tile_width, self.board_tile_height), QImage(self.image_path + "collect.png")) elif self.is_hub_tile(row, col): painter.drawImage( QRect(x, y, self.board_tile_width, self.board_tile_height), QImage(self.image_path + "win.png")) # Quadrant One elif row == 1 and col == 1: painter.drawImage( QRect(self.board_tile_width, self.board_tile_height, self.board_tile_width * 3, self.board_tile_height * 3), QImage(self.image_path + "american_flag.jpeg")) # Quadrant Two elif row == 5 and col == 1: painter.drawImage( QRect(self.board_tile_width * row, self.board_tile_height, self.board_tile_width * 3, self.board_tile_height * 3), QImage(self.image_path + "fireworks-two.jpg")) # Quadrant Three elif row == 1 and col == 5: painter.drawImage( QRect(self.board_tile_width, self.board_tile_height * col, self.board_tile_width * 3, self.board_tile_height * 3), QImage(self.image_path + "underwear_guy.jpeg")) # Quadrant Four elif row == 5 and col == 5: painter.drawImage( QRect(self.board_tile_width * row, self.board_tile_height * col, self.board_tile_width * 3, self.board_tile_height * 3), QImage(self.image_path + "doi.jpg")) # end if # Update to x-coordinate for next tile x = x + self.board_tile_width # end for # Reset (x,y) starting coordinates for next row and columns y = y + self.board_tile_height x = 0 # end for self.board_initialized = True
class MainWindow(QtWidgets.QMainWindow): def __init__(self, widget, data): # super().__init__() QtWidgets.QMainWindow.__init__(self) self.setWindowTitle("Simple Podcast Utility") self.widget = widget self.podcast = podcast self.items = None self.setCentralWidget(widget) self.player = QMediaPlayer() self.media = None # Menu self.menu = QtWidgets.QMenuBar() # self.menu = self.menuBar() self.menu.setNativeMenuBar(False) self.setMenuBar(self.menu) self.file_menu = self.menu.addMenu("File") add_action = QtWidgets.QAction("Add", self) exit_action = QtWidgets.QAction("Exit", self) self.file_menu.addAction(add_action) self.file_menu.addAction(exit_action) add_action.triggered.connect(self.add_podcast) exit_action.triggered.connect(self.exit_app) names = self.get_podcast_name_list(self.podcast.get_subscribe()) self.widget.update_podcasts_list(names) self.widget.podcasts_list.clicked.connect(self.update_item_list) self.widget.item_list.doubleClicked.connect(self.start_play_item) self.widget.progress_bar.sliderPressed.connect( self.on_select_progress_begin) self.widget.progress_bar.sliderReleased.connect( self.on_select_progress_end) self.widget.progress_bar.sliderMoved.connect( self.on_select_progress_move) self.timer = QTimer() self.timer.timeout.connect(self.on_timer) self.timer.start(1000) self.begin_seek = False self.play_url = None @Slot() def on_select_progress_begin(self): self.begin_seek = True @Slot() def on_select_progress_move(self, value): self.widget.playtime_label.setText(time_string(value)) @Slot() def on_select_progress_end(self): if self.player.isSeekable(): value = self.widget.progress_bar.value() self.player.setPosition(value * 1000) self.begin_seek = False else: print('not seekable') @Slot() def on_timer(self): player = self.player if not self.begin_seek: if player.state() == QMediaPlayer.PlayingState: playtime = player.position() // 1000 self.widget.set_progress(playtime) @Slot() def start_play_item(self, index): i = index.row() if self.player.state() == QMediaPlayer.PlayingState: self.player.stop() self.begin_seek = False self.play_url = self.items[i]['url'] self.media = QMediaContent(self.items[i]['url']) self.player.setMedia(self.media) self.player.play() self.widget.set_duration(self.items[i]['duration']) @Slot() def update_item_list(self, index): i = index.row() feed_url = self.podcast.podcasts[i]['feedUrl'] self.items = podcast.get_feed(feed_url) names = self.get_item_name_list(self.items) self.widget.update_items_list(names) @Slot() def subscribe(self, index): i = index.row() self.podcast.subscribe(self.search_r[i]) names = self.get_podcast_name_list(self.podcast.get_subscribe()) self.widget.update_podcasts_list(names) @Slot() def search(self): self.search_r = self.podcast.search(self.dialog.edit.text()) names = [] if self.search_r: for i in self.search_r: names.append(i['collectionName']) model = QStringListModel(names) self.dialog.result_list.setModel(model) def get_item_name_list(self, items): names = [] for item in items: names.append(item['title']) return names def get_podcast_name_list(self, podcasts): names = [] for item in podcasts: names.append(item['collectionName']) return names @Slot() def add_podcast(self, checked): self.dialog = SearchDialog(self.subscribe, self.search) self.dialog.exec_() self.dialog = None @Slot() def exit_app(self, checked): print('exit app') QtWidgets.QApplication.quit()
class SoundPlayer: def __init__(self, soundfile, parent): self.soundfile = soundfile self.isplaying = False self.time = 0 # current audio position in frames self.audio = QMediaPlayer() self.decoder = QAudioDecoder() self.is_loaded = False self.volume = 100 self.isplaying = False self.decoded_audio = {} self.only_samples = [] self.decoding_is_finished = False self.max_bits = 32768 self.signed = False # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works self.audio.durationChanged.connect(self.on_durationChanged) self.decoder.finished.connect(self.decode_finished_signal) self.audio.setMedia(QUrl.fromLocalFile(soundfile)) self.decoder.setSourceFilename(soundfile) # strangely inconsistent file-handling # It will hang here forever if we don't process the events. while not self.is_loaded: QCoreApplication.processEvents() time.sleep(0.1) self.decode_audio() self.np_data = np.array(self.only_samples) if not self.signed: # don't ask me why this fixes 8 bit samples... self.np_data = self.np_data - self.max_bits / 2 print(len(self.only_samples)) print(self.max_bits) self.isvalid = True def audioformat_to_datatype(self, audioformat): num_bits = audioformat.sampleSize() signed = audioformat.sampleType() self.max_bits = 2 ** int(num_bits) if signed == QAudioFormat.SampleType.UnSignedInt: self.signed = False return "uint" + str(num_bits) + "_t" elif signed == QAudioFormat.SampleType.SignedInt: self.signed = True self.max_bits = int(self.max_bits / 2) return "int" + str(num_bits) + "_t" def decode_audio(self): self.decoder.start() while not self.decoding_is_finished: QCoreApplication.processEvents() if self.decoder.bufferAvailable(): tempdata = self.decoder.read() # We use the Pointer Address to get a cffi Pointer to the data (hopefully) cast_data = self.audioformat_to_datatype(tempdata.format()) possible_data = ffi.cast("{1}[{0}]".format(tempdata.sampleCount(), cast_data), int(tempdata.constData())) self.only_samples.extend(possible_data) self.decoded_audio[self.decoder.position()] = [possible_data, len(possible_data), tempdata.byteCount(), tempdata.format()] def decode_finished_signal(self): self.decoding_is_finished = True def on_durationChanged(self, duration): print("Changed!") print(duration) self.is_loaded = True def get_audio_buffer(self, bufferdata): print(bufferdata) def IsValid(self): return self.isvalid def Duration(self): return self.audio.duration() / 1000.0 def GetRMSAmplitude(self, time, sampleDur): # time_start = time * (len(self.only_samples)/self.Duration()) # time_end = (time + sampleDur) * (len(self.only_samples)/self.Duration()) # samples = self.only_samples[int(time_start):int(time_end)] time_start = time * (len(self.np_data) / self.Duration()) time_end = (time + sampleDur) * (len(self.np_data) / self.Duration()) samples = self.np_data[int(time_start):int(time_end)] if len(samples): return np.sqrt(np.mean(samples ** 2)) else: return 1 def is_playing(self): if self.audio.state() == QMediaPlayer.PlayingState: return True else: return False def set_cur_time(self, newtime): self.time = newtime * 1000.0 self.audio.setPosition(self.time) def stop(self): self.isplaying = False self.audio.stop() def current_time(self): self.time = self.audio.position() / 1000.0 return self.time def set_volume(self, newvolume): self.volume = newvolume self.audio.setVolume(self.volume) def play(self, arg): self.isplaying = True # TODO: We should be able to replace isplaying with queries to self.audio.state() self.audio.play() def play_segment(self, start, length): print("Playing Segment") if not self.is_playing(): # otherwise this get's kinda echo-y self.isplaying = True self.audio.setPosition(start * 1000.0) self.audio.play() thread.start_new_thread(self._wait_for_segment_end, (start, length)) def _wait_for_segment_end(self, newstart, newlength): start = newstart * 1000.0 length = newlength * 1000.0 end = start + length print(start) print(length) print(end) while self.audio.position() < end: if not self.isplaying: return 0 QCoreApplication.processEvents() print(self.audio.position()) time.sleep(0.001) self.audio.stop() self.isplaying = False
class MainWindow(QMainWindow): # Main window def __init__(self): super().__init__() self.setWindowTitle = 'DD烤肉机' self.resize(1870, 820) self.mainWidget = QWidget() self.mainLayout = QGridLayout() # Grid layout self.mainLayout.setSpacing(10) self.mainWidget.setLayout(self.mainLayout) self.duration = 60000 self.bitrate = 2000 self.fps = 60 self.initProcess = InitProcess() self.previewSubtitle = PreviewSubtitle() self.dnldWindow = YoutubeDnld() self.exportWindow = exportSubtitle() self.videoDecoder = VideoDecoder() self.exportWindow.exportArgs.connect(self.exportSubtitle) self.stack = QStackedWidget() self.stack.setFixedWidth(1300) self.mainLayout.addWidget(self.stack, 0, 0, 10, 8) buttonWidget = QWidget() buttonLayout = QHBoxLayout() buttonWidget.setLayout(buttonLayout) self.playButton = QPushButton('从本地打开') self.playButton.clicked.connect(self.open) self.playButton.setFixedWidth(400) self.playButton.setFixedHeight(75) self.dnldButton = QPushButton('Youtube下载器') self.dnldButton.clicked.connect(self.popDnld) self.dnldButton.setFixedWidth(400) self.dnldButton.setFixedHeight(75) buttonLayout.addWidget(self.playButton) buttonLayout.addWidget(self.dnldButton) self.stack.addWidget(buttonWidget) self.videoPath = '' self.videoWidth = 1920 self.videoHeight = 1080 self.globalInterval = 200 self.setPlayer() self.setSubtitle() self.setToolBar() self.setCentralWidget(self.mainWidget) self.playStatus = False self.volumeStatus = True self.volumeValue = 100 self.subSelectedTxt = '' self.subReplayTime = 1 self.clipBoard = [] self.grabKeyboard() self.show() def setPlayer(self): self.playerWidget = QGraphicsVideoItem() self.scene = QGraphicsScene() self.view = QGraphicsView(self.scene) self.view.resize(1280, 730) self.scene.addItem(self.playerWidget) self.stack.addWidget(self.view) self.player = QMediaPlayer(self, QMediaPlayer.VideoSurface) self.player.setVideoOutput(self.playerWidget) self.view.installEventFilter(self) self.view.show() self.srtTextItemDict = {0: QGraphicsTextItem(), 1: QGraphicsTextItem(), 2: QGraphicsTextItem(), 3: QGraphicsTextItem(), 4: QGraphicsTextItem()} for _, srtTextItem in self.srtTextItemDict.items(): self.scene.addItem(srtTextItem) def setSubtitle(self): self.subtitleDict = {x: {-1: [100, '']} for x in range(5)} self.subTimer = QTimer() self.subTimer.setInterval(100) self.subtitle = QTableWidget() self.subtitle.setAutoScroll(False) self.subtitle.setEditTriggers(QAbstractItemView.NoEditTriggers) self.mainLayout.addWidget(self.subtitle, 0, 8, 10, 12) self.subtitle.setColumnCount(5) self.subtitle.selectRow(0) self.subtitle.setHorizontalHeaderLabels(['%s' % (i + 1) for i in range(5)]) self.subtitle.setVerticalHeaderLabels([cnt2Time2(i, self.globalInterval) for i in range(self.subtitle.rowCount())]) for index in range(5): self.subtitle.setColumnWidth(index, 130) self.subtitle.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel) self.subtitle.setEditTriggers(QAbstractItemView.DoubleClicked) self.subtitle.horizontalHeader().sectionClicked.connect(self.addSubtitle) self.subtitle.doubleClicked.connect(self.releaseKeyboard) self.subtitle.cellChanged.connect(self.subEdit) self.subtitle.verticalHeader().sectionClicked.connect(self.subHeaderClick) self.subtitle.setContextMenuPolicy(Qt.CustomContextMenu) self.subtitle.customContextMenuRequested.connect(self.popTableMenu) self.initSubtitle() def initSubtitle(self): self.initProcess.show() self.subtitle.cellChanged.disconnect(self.subEdit) for x in range(self.subtitle.columnCount()): for y in range(self.subtitle.rowCount()): self.subtitle.setSpan(y, x, 1, 1) self.subtitle.setRowCount(self.duration // self.globalInterval + 1) for x in range(self.subtitle.columnCount()): for y in range(self.subtitle.rowCount()): self.subtitle.setItem(y, x, QTableWidgetItem('')) self.subtitle.item(y, x).setBackground(QBrush(QColor('#232629'))) self.subtitle.setVerticalHeaderLabels([cnt2Time2(i, self.globalInterval) for i in range(self.subtitle.rowCount())]) self.subtitle.cellChanged.connect(self.subEdit) self.initProcess.hide() def addSubtitle(self, index): subtitlePath = QFileDialog.getOpenFileName(self, "请选择字幕", None, "字幕文件 (*.srt *.vtt *.ass *.ssa)")[0] if subtitlePath: self.initProcess.show() self.subtitle.cellChanged.disconnect(self.subEdit) if subtitlePath.endswith('.ass') or subtitlePath.endswith('.ssa'): p = subprocess.Popen(['utils/ffmpeg.exe', '-y', '-i', subtitlePath, 'temp_sub.srt']) p.wait() subtitlePath = 'temp_sub.srt' subData = {} with open(subtitlePath, 'r', encoding='utf-8') as f: f = f.readlines() subText = '' YoutubeAutoSub = False for l in f: if '<c>' in l: YoutubeAutoSub = True break for cnt, l in enumerate(f): if '<c>' in l: lineData = l.split('c>') if len(lineData) > 3: subText, start, _ = lineData[0].split('<') start = calSubTime(start[:-1]) // self.globalInterval * self.globalInterval if start not in self.subtitleDict[index]: end = calSubTime(lineData[-3][1:-2]) // self.globalInterval * self.globalInterval for i in range(len(lineData) // 2): subText += lineData[i * 2 + 1][:-2] subData[start] = [end - start, subText] else: subText, start, _ = lineData[0].split('<') start = calSubTime(start[:-1]) // self.globalInterval * self.globalInterval if start not in self.subtitleDict[index]: subText += lineData[1][:-2] subData[start] = [self.globalInterval, subText] elif '-->' in l and f[cnt + 2].strip() and '<c>' not in f[cnt + 2]: subText = f[cnt + 2][:-1] start = calSubTime(l[:12]) // self.globalInterval * self.globalInterval if start not in self.subtitleDict[index]: end = calSubTime(l[17:29]) // self.globalInterval * self.globalInterval subData[start] = [end - start, subText] if '-->' in l and f[cnt + 1].strip() and not YoutubeAutoSub: start = calSubTime(l[:12]) // self.globalInterval * self.globalInterval if start not in self.subtitleDict[index]: end = calSubTime(l[17:29]) // self.globalInterval * self.globalInterval delta = end - start if delta > 10: if '<b>' in f[cnt + 1]: subData[start] = [delta, f[cnt + 1].split('<b>')[1].split('<')[0]] else: subData[start] = [delta, f[cnt + 1][:-1]] self.subtitleDict[index].update(subData) maxRow = 0 for _, v in self.subtitleDict.items(): startMax = max(v.keys()) rowCount = (startMax + v[startMax][0]) // self.globalInterval if rowCount > maxRow: maxRow = rowCount if maxRow < self.duration // self.globalInterval + 1: maxRow = self.duration // self.globalInterval else: self.duration = maxRow * self.globalInterval self.subtitle.setRowCount(maxRow) self.subtitle.setVerticalHeaderLabels([cnt2Time2(i, self.globalInterval) for i in range(self.subtitle.rowCount())]) for start, rowData in subData.items(): startRow = start // self.globalInterval endRow = startRow + rowData[0] // self.globalInterval for row in range(startRow, endRow): self.subtitle.setItem(row, index, QTableWidgetItem(rowData[1])) self.subtitle.item(row, index).setBackground(QBrush(QColor('#35545d'))) self.subtitle.setSpan(startRow, index, endRow - startRow, 1) self.refreshComboBox() self.subtitle.cellChanged.connect(self.subEdit) self.initProcess.hide() def subTimeOut(self): fontColor = self.previewSubtitle.fontColor fontSize = (self.previewSubtitle.fontSize + 5) / 2.5 fontBold = self.previewSubtitle.bold fontItalic = self.previewSubtitle.italic fontShadowOffset = self.previewSubtitle.shadowOffset for _, srtTextItem in self.srtTextItemDict.items(): srtTextItem.setDefaultTextColor(fontColor) font = QFont() font.setFamily("微软雅黑") font.setPointSize(fontSize) font.setBold(fontBold) font.setItalic(fontItalic) srtTextItem.setFont(font) srtTextShadow = QGraphicsDropShadowEffect() srtTextShadow.setOffset(fontShadowOffset) srtTextItem.setGraphicsEffect(srtTextShadow) try: selected = self.subtitle.selectionModel().selection().indexes() for x, i in enumerate(selected): if self.subtitle.item(i.row(), x): txt = self.subtitle.item(i.row(), x).text() if txt: self.srtTextItemDict[x].setPlainText('#%s:' % (x + 1) + txt) txtSize = self.srtTextItemDict[x].boundingRect().size() posY = self.playerWidget.size().height() - txtSize.height() * (x + 1) posX = (self.playerWidget.size().width() - txtSize.width()) / 2 self.srtTextItemDict[x].setPos(posX, posY) else: self.srtTextItemDict[x].setPlainText('') else: self.srtTextItemDict[x].setPlainText('') except: pass def subHeaderClick(self, index): if self.player.duration(): position = index * self.globalInterval self.player.setPosition(position) self.videoSlider.setValue(position * 1000 // self.player.duration()) self.setTimeLabel() def subEdit(self, row, index): repeat = self.subtitle.rowSpan(row, index) self.setSubtitleDict(row, index, repeat, self.subtitle.item(row, index).text()) self.subtitle.cellChanged.disconnect(self.subEdit) for cnt in range(repeat): if self.subtitle.item(row + cnt, index).text(): self.subtitle.item(row, index).setBackground(QBrush(QColor('#35545d'))) else: self.subtitle.item(row, index).setBackground(QBrush(QColor('#232629'))) self.subtitle.cellChanged.connect(self.subEdit) def setSubtitleDict(self, row, index, num, text): self.subtitleDict[index][row * self.globalInterval] = [num * self.globalInterval, text] def popTableMenu(self, pos): self.subtitle.cellChanged.disconnect(self.subEdit) pos = QPoint(pos.x() + 55, pos.y() + 30) menu = QMenu() copy = menu.addAction('复制') paste = menu.addAction('粘贴') setSpan = menu.addAction('合并') clrSpan = menu.addAction('拆分') addSub = menu.addAction('导入字幕') cutSub = menu.addAction('裁剪字幕') action = menu.exec_(self.subtitle.mapToGlobal(pos)) selected = self.subtitle.selectionModel().selection().indexes() yList = [selected[0].row(), selected[-1].row()] xSet = set() for i in range(len(selected)): xSet.add(selected[i].column()) if action == copy: for x in xSet: self.clipBoard = [] for y in range(yList[0], yList[1] + 1): if self.subtitle.item(y, x): self.clipBoard.append(self.subtitle.item(y, x).text()) else: self.clipBoard.append('') break elif action == paste: self.subtitle.cellChanged.connect(self.subEdit) for x in xSet: for cnt, text in enumerate(self.clipBoard): self.subtitle.setItem(yList[0] + cnt, x, QTableWidgetItem(text)) self.subtitleDict[x][(yList[0] + cnt) * self.globalInterval] = [self.globalInterval, text] self.subtitle.cellChanged.disconnect(self.subEdit) elif action == setSpan: for x in xSet: if not self.subtitle.item(yList[0], x): firstItem = '' else: firstItem = self.subtitle.item(yList[0], x).text() for y in range(yList[0], yList[1] + 1): self.subtitle.setSpan(y, x, 1, 1) self.subtitle.setItem(y, x, QTableWidgetItem(firstItem)) self.subtitle.item(y, x).setBackground(QBrush(QColor('#35545d'))) if y * self.globalInterval in self.subtitleDict[x]: del self.subtitleDict[x][y * self.globalInterval] for x in xSet: self.subtitle.setSpan(yList[0], x, yList[1] - yList[0] + 1, 1) self.setSubtitleDict(yList[0], x, yList[1] - yList[0] + 1, firstItem) elif action == clrSpan: for x in xSet: if not self.subtitle.item(yList[0], x): firstItem = '' else: firstItem = self.subtitle.item(yList[0], x).text() for cnt, y in enumerate(range(yList[0], yList[1] + 1)): self.subtitle.setSpan(y, x, 1, 1) if not cnt: self.subtitle.setItem(yList[0], x, QTableWidgetItem(firstItem)) if firstItem: self.subtitle.item(y, x).setBackground(QBrush(QColor('#35545d'))) else: self.subtitle.item(y, x).setBackground(QBrush(QColor('#232629'))) else: self.subtitle.setItem(y, x, QTableWidgetItem('')) self.subtitle.item(y, x).setBackground(QBrush(QColor('#232629'))) self.setSubtitleDict(yList[0], x, yList[1] - yList[0] + 1, firstItem) break elif action == addSub: self.subtitle.cellChanged.connect(self.subEdit) for x in xSet: self.addSubtitle(x) self.subtitle.cellChanged.disconnect(self.subEdit) elif action == cutSub: for x in xSet: start = yList[0] * self.globalInterval end = yList[1] * self.globalInterval self.exportSubWindow(start, end, x + 1) self.subtitle.cellChanged.connect(self.subEdit) def setToolBar(self): ''' menu bar, file menu, play menu, tool bar. ''' toolBar = QToolBar() self.setContextMenuPolicy(Qt.NoContextMenu) self.addToolBar(toolBar) fileMenu = self.menuBar().addMenu('&文件') openAction = QAction(QIcon.fromTheme('document-open'), '&打开...', self, shortcut=QKeySequence.Open, triggered=self.open) fileMenu.addAction(openAction) downloadAction = QAction(QIcon.fromTheme('document-open'), '&Youtube下载器', self, triggered=self.popDnld) fileMenu.addAction(downloadAction) exitAction = QAction(QIcon.fromTheme('application-exit'), '&退出', self, shortcut='Ctrl+Q', triggered=self.close) fileMenu.addAction(exitAction) playMenu = self.menuBar().addMenu('&功能') self.playIcon = self.style().standardIcon(QStyle.SP_MediaPlay) self.pauseIcon = self.style().standardIcon(QStyle.SP_MediaPause) self.playAction = toolBar.addAction(self.playIcon, '播放') self.playAction.triggered.connect(self.mediaPlay) self.volumeIcon = self.style().standardIcon(QStyle.SP_MediaVolume) self.volumeMuteIcon = self.style().standardIcon(QStyle.SP_MediaVolumeMuted) self.volumeAction = toolBar.addAction(self.volumeIcon, '静音') self.volumeAction.triggered.connect(self.volumeMute) previewAction = QAction(QIcon.fromTheme('document-open'), '&设置预览字幕', self, triggered=self.popPreview) playMenu.addAction(previewAction) decodeMenu = self.menuBar().addMenu('&输出') decodeAction = QAction(QIcon.fromTheme('document-open'), '&输出字幕及视频', self, triggered=self.decode) decodeMenu.addAction(decodeAction) self.volSlider = Slider() self.volSlider.setOrientation(Qt.Horizontal) self.volSlider.setMinimum(0) self.volSlider.setMaximum(100) self.volSlider.setFixedWidth(120) self.volSlider.setValue(self.player.volume()) self.volSlider.setToolTip(str(self.volSlider.value())) self.volSlider.pointClicked.connect(self.setVolume) toolBar.addWidget(self.volSlider) self.videoPositionEdit = LineEdit('00:00') self.videoPositionEdit.setAlignment(Qt.AlignRight) self.videoPositionEdit.setFixedWidth(75) self.videoPositionEdit.setFont(QFont('Timers', 14)) self.videoPositionEdit.clicked.connect(self.mediaPauseOnly) self.videoPositionEdit.editingFinished.connect(self.mediaPlayOnly) self.videoPositionLabel = QLabel(' / 00:00 ') self.videoPositionLabel.setFont(QFont('Timers', 14)) toolBar.addWidget(QLabel(' ')) toolBar.addWidget(self.videoPositionEdit) toolBar.addWidget(self.videoPositionLabel) self.timer = QTimer() self.timer.setInterval(100) self.videoSlider = Slider() self.videoSlider.setEnabled(False) self.videoSlider.setOrientation(Qt.Horizontal) self.videoSlider.setMinimum(0) self.videoSlider.setMaximum(1000) self.videoSlider.setFixedWidth(1000) self.videoSlider.sliderMoved.connect(self.timeStop) self.videoSlider.sliderReleased.connect(self.timeStart) self.videoSlider.pointClicked.connect(self.videoSliderClick) toolBar.addWidget(self.videoSlider) toolBar.addWidget(QLabel(' ')) self.globalIntervalComBox = QComboBox() self.globalIntervalComBox.addItems(['间隔 100ms', '间隔 200ms', '间隔 500ms', '间隔 1s']) self.globalIntervalComBox.setCurrentIndex(1) self.globalIntervalComBox.currentIndexChanged.connect(self.setGlobalInterval) toolBar.addWidget(self.globalIntervalComBox) toolBar.addWidget(QLabel(' ')) self.subEditComBox = QComboBox() self.refreshComboBox() toolBar.addWidget(self.subEditComBox) toolBar.addWidget(QLabel(' ')) moveForward = QPushButton('- 1') moveForward.setFixedWidth(50) toolBar.addWidget(moveForward) toolBar.addWidget(QLabel(' ')) moveAfterward = QPushButton('+ 1') moveAfterward.setFixedWidth(50) toolBar.addWidget(moveAfterward) toolBar.addWidget(QLabel(' ')) clearSub = QPushButton('清空') clearSub.setFixedWidth(50) toolBar.addWidget(clearSub) toolBar.addWidget(QLabel(' ')) outputSub = QPushButton('裁剪') outputSub.setFixedWidth(50) toolBar.addWidget(outputSub) moveForward.clicked.connect(self.moveForward) moveAfterward.clicked.connect(self.moveAfterward) clearSub.clicked.connect(self.clearSub) outputSub.clicked.connect(self.exportSubWindow) def setGlobalInterval(self, index): if not self.playStatus: self.mediaPlay() self.globalInterval = {0: 100, 1: 200, 2: 500, 3: 1000}[index] self.initSubtitle() self.initProcess.show() self.subtitle.cellChanged.disconnect(self.subEdit) for index, subData in self.subtitleDict.items(): for start, rowData in subData.items(): startRow = start // self.globalInterval deltaRow = rowData[0] // self.globalInterval if deltaRow: endRow = startRow + deltaRow for row in range(startRow, endRow): self.subtitle.setItem(row, index, QTableWidgetItem(rowData[1])) if row >= 0: self.subtitle.item(row, index).setBackground(QBrush(QColor('#35545d'))) self.subtitle.setSpan(startRow, index, endRow - startRow, 1) self.subtitle.cellChanged.connect(self.subEdit) self.initProcess.hide() def moveForward(self): self.initProcess.show() self.subtitle.cellChanged.disconnect(self.subEdit) index = self.subEditComBox.currentIndex() for y in range(self.subtitle.rowCount()): self.subtitle.setSpan(y, index, 1, 1) self.subtitle.setItem(y, index, QTableWidgetItem('')) self.subtitle.item(y, index).setBackground(QBrush(QColor('#232629'))) tmpDict = self.subtitleDict[index] self.subtitleDict[index] = {} for start, rowData in tmpDict.items(): self.subtitleDict[index][start - self.globalInterval] = rowData for start, rowData in self.subtitleDict[index].items(): startRow = start // self.globalInterval endRow = startRow + rowData[0] // self.globalInterval for row in range(startRow, endRow): self.subtitle.setItem(row, index, QTableWidgetItem(rowData[1])) self.subtitle.item(row, index).setBackground(QBrush(QColor('#35545d'))) self.subtitle.setSpan(startRow, index, endRow - startRow, 1) self.subtitle.cellChanged.connect(self.subEdit) self.initProcess.hide() def moveAfterward(self): self.initProcess.show() self.subtitle.cellChanged.disconnect(self.subEdit) index = self.subEditComBox.currentIndex() for y in range(self.subtitle.rowCount()): self.subtitle.setSpan(y, index, 1, 1) self.subtitle.setItem(y, index, QTableWidgetItem('')) self.subtitle.item(y, index).setBackground(QBrush(QColor('#232629'))) tmpDict = self.subtitleDict[index] self.subtitleDict[index] = {} for start, rowData in tmpDict.items(): self.subtitleDict[index][start + self.globalInterval] = rowData for start, rowData in self.subtitleDict[index].items(): startRow = start // self.globalInterval endRow = startRow + rowData[0] // self.globalInterval for row in range(startRow, endRow): self.subtitle.setItem(row, index, QTableWidgetItem(rowData[1])) self.subtitle.item(row, index).setBackground(QBrush(QColor('#35545d'))) self.subtitle.setSpan(startRow, index, endRow - startRow, 1) self.subtitle.cellChanged.connect(self.subEdit) self.initProcess.hide() def clearSub(self): index = self.subEditComBox.currentIndex() reply = QMessageBox.information(self, '清空字幕', '清空第 %s 列字幕条?' % (index + 1), QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: self.initProcess.show() self.subtitle.cellChanged.disconnect(self.subEdit) self.subtitleDict[index] = {0: [self.globalInterval, '']} for i in range(self.subtitle.rowCount()): self.subtitle.setSpan(i, index, 1, 1) self.subtitle.setItem(i, index, QTableWidgetItem('')) self.subtitle.item(i, index).setBackground(QBrush(QColor('#232629'))) self.subtitle.setHorizontalHeaderItem(index, QTableWidgetItem('%s' % (index + 1))) self.subtitle.cellChanged.connect(self.subEdit) self.initProcess.hide() def exportSubWindow(self, start=0, end=0, index=None): self.releaseKeyboard() self.exportWindow.hide() self.exportWindow.show() start = '00:00.0' if not start else self.splitTime(start) end = self.splitTime(self.duration) if not end else self.splitTime(end) if not index: index = self.subEditComBox.currentIndex() + 1 self.exportWindow.setDefault(start, end, index) def exportSubtitle(self, exportArgs): start = calSubTime2(exportArgs[0]) end = calSubTime2(exportArgs[1]) subStart = calSubTime2(exportArgs[2]) index = exportArgs[3] - 1 subData = self.subtitleDict[index] rowList = sorted(subData.keys()) exportRange = [] for t in rowList: if t >= start and t <= end: exportRange.append(t) subNumber = 1 with open(exportArgs[-1], 'w', encoding='utf-8') as exportFile: for t in exportRange: text = subData[t][1] if text: start = ms2Time(t + subStart) end = ms2Time(t + subStart + subData[t][0]) exportFile.write('%s\n%s --> %s\n%s\n\n' % (subNumber, start, end, text)) subNumber += 1 QMessageBox.information(self, '导出字幕', '导出完成', QMessageBox.Yes) self.exportWindow.hide() def refreshComboBox(self): self.subEditComBox.clear() for i in range(self.subtitle.columnCount()): self.subEditComBox.addItem('字幕 ' + str(i + 1)) def open(self): self.videoPath = QFileDialog.getOpenFileName(self, "请选择视频文件", None, "MP4格式 (*.mp4);;所有文件(*.*)")[0] if self.videoPath: cmd = ['utils/ffmpeg.exe', '-i', self.videoPath] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.wait() for l in p.stdout.readlines(): l = l.decode('utf8') if 'Duration' in l: self.duration = calSubTime(l.split(' ')[3][:-1]) if 'Stream' in l and 'DAR' in l: self.videoWidth, self.videoHeight = map(int, l.split(' [')[0].split(' ')[-1].split('x')) args = l.split(',') for cnt, arg in enumerate(args): if 'kb' in arg: self.bitrate = int(arg.split('kb')[0]) self.fps = int(args[cnt + 1].split('fps')[0]) break break self.initProcess.show() self.subtitle.cellChanged.disconnect(self.subEdit) self.subtitle.setRowCount(self.duration // self.globalInterval + 1) self.subtitle.setVerticalHeaderLabels([cnt2Time2(i, self.globalInterval) for i in range(self.subtitle.rowCount())]) self.subtitle.cellChanged.connect(self.subEdit) self.initProcess.hide() url = QUrl.fromLocalFile(self.videoPath) self.stack.setCurrentIndex(1) self.playerWidget.setSize(QSizeF(1280, 720)) self.player.setMedia(url) self.playStatus = True self.videoSlider.setEnabled(True) self.mediaPlay() self.timer.start() self.timer.timeout.connect(self.timeOut) self.subTimer.start() self.subTimer.timeout.connect(self.subTimeOut) def popDnld(self): self.releaseKeyboard() self.dnldWindow.hide() self.dnldWindow.show() def popPreview(self): self.releaseKeyboard() self.previewSubtitle.hide() self.previewSubtitle.show() def decode(self): self.releaseKeyboard() self.videoDecoder.setDefault(self.videoPath, self.videoWidth, self.videoHeight, self.duration, self.bitrate, self.fps, self.subtitleDict) self.videoDecoder.hide() self.videoDecoder.show() def mediaPlay(self): if self.playStatus: self.player.play() self.grabKeyboard() self.timeStart() self.playStatus = False self.playAction.setIcon(self.pauseIcon) self.playAction.setText('暂停') else: self.player.pause() self.timeStop() self.playStatus = True self.playAction.setIcon(self.playIcon) self.playAction.setText('播放') def mediaPlayOnly(self): self.grabKeyboard() try: timeText = self.videoPositionEdit.text().split(':') m, s = timeText[:2] if not m: m = '00' if not s: s = '00' if len(m) > 3: m = m[:3] if len(s) > 2: s = s[:2] if m.isdigit(): m = int(m) if s.isdigit(): s = int(s) if s > 60: s = 60 total_m = self.player.duration() // 60000 if m > total_m: m = total_m self.player.setPosition(m * 60000 + s * 1000) self.videoSlider.setValue(self.player.position() * 1000 / self.player.duration()) except: pass self.videoPositionEdit.setReadOnly(True) self.timeStart() def mediaPauseOnly(self): self.releaseKeyboard() self.videoPositionEdit.setReadOnly(False) self.player.pause() self.timeStop() self.playStatus = True self.playAction.setIcon(self.playIcon) self.playAction.setText('播放') def splitTime(self, playTime): playTime = playTime // 1000 m = str(playTime // 60) s = playTime % 60 s = ('0%s' % s)[-2:] if len(m) > 2: t = '%3s:%2s' % (m, s) else: t = '%2s:%2s' % (m, s) return t def timeOut(self): row = self.player.position() // self.globalInterval self.subtitle.selectRow(row) self.subtitle.verticalScrollBar().setValue(row - 10) if self.dnldWindow.isHidden() or self.exportWindow.isHidden() or self.videoDecoder.isHidden(): self.grabKeyboard() try: self.videoSlider.setValue(self.player.position() * 1000 / self.player.duration()) self.setTimeLabel() except: pass def timeStop(self): self.timer.stop() def timeStart(self): self.timer.start() def videoSliderClick(self, p): self.videoSlider.setValue(p.x()) self.player.setPosition(p.x() * self.player.duration() // 1000) self.setTimeLabel() def setVolume(self, p): self.volumeValue = p.x() if self.volumeValue > 100: self.volumeValue = 100 if self.volumeValue < 0: self.volumeValue = 0 self.volSlider.setValue(self.volumeValue) self.player.setVolume(self.volumeValue) self.volSlider.setToolTip(str(self.volSlider.value())) if self.volumeValue: self.volumeStatus = True self.volumeAction.setIcon(self.volumeIcon) else: self.volumeStatus = False self.volumeAction.setIcon(self.volumeMuteIcon) def volumeMute(self): if self.volumeStatus: self.volumeStatus = False self.old_volumeValue = self.player.volume() self.player.setVolume(0) self.volSlider.setValue(0) self.volumeAction.setIcon(self.volumeMuteIcon) else: self.volumeStatus = True self.player.setVolume(self.old_volumeValue) self.volSlider.setValue(self.old_volumeValue) self.volumeAction.setIcon(self.volumeIcon) def setTimeLabel(self): now = self.player.position() total = self.player.duration() now = self.splitTime(now) total = self.splitTime(total) self.videoPositionEdit.setText(now) self.videoPositionLabel.setText(' / %s ' % total) def eventFilter(self, obj, event): if obj == self.view: if event.type() == QEvent.MouseButtonPress: self.mediaPlay() return QMainWindow.eventFilter(self, obj, event) def keyPressEvent(self, QKeyEvent): key = QKeyEvent.key() if key == Qt.Key_Left: if self.videoSlider.isEnabled(): self.player.setPosition(self.player.position() - 5000) self.videoSlider.setValue(self.player.position() * 1000 / self.player.duration()) self.setTimeLabel() elif key == Qt.Key_Right: if self.videoSlider.isEnabled(): self.player.setPosition(self.player.position() + 5000) self.videoSlider.setValue(self.player.position() * 1000 / self.player.duration()) self.setTimeLabel() elif key == Qt.Key_Up: self.volumeValue += 10 if self.volumeValue > 100: self.volumeValue = 100 self.volSlider.setValue(self.volumeValue) self.player.setVolume(self.volumeValue) elif key == Qt.Key_Down: self.volumeValue -= 10 if self.volumeValue < 0: self.volumeValue = 0 self.volSlider.setValue(self.volumeValue) self.player.setVolume(self.volumeValue) elif key == Qt.Key_Space: self.mediaPlay()
class MainWindow(QObject): #class constructor def __init__(self, ui_file, parent=None): #reference to our music player self.music_player = QMediaPlayer() self.music_player.setVolume(100) #call parent QObject constructor super(MainWindow, self).__init__(parent) #load the UI file into Python ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) loader = QUiLoader() self.window = loader.load(ui_file) #always remember to close files ui_file.close() #add event listeners open_action = self.window.findChild(QAction, 'action_open') open_action.triggered.connect(self.open_action_triggered) quit_action = self.window.findChild(QAction, 'action_quit') quit_action.triggered.connect(self.quit_action_triggered) play_button = self.window.findChild(QPushButton, 'play_button') play_button.clicked.connect(self.play_button_clicked) pause_button = self.window.findChild(QPushButton, 'pause_button') pause_button.clicked.connect(self.pause_button_clicked) stop_button = self.window.findChild(QPushButton, 'stop_button') stop_button.clicked.connect(self.stop_button_clicked) raise_volume_button = self.window.findChild(QPushButton, 'raise_volume_button') raise_volume_button.clicked.connect(self.raise_volume_button_clicked) lower_volume_button = self.window.findChild(QPushButton, 'lower_volume_button') lower_volume_button.clicked.connect(self.lower_volume_button_clicked) #show window to user self.window.show() def open_action_triggered(self): file_name = QFileDialog.getOpenFileName(self.window) self.music_player.setMedia(QUrl.fromLocalFile(file_name[0])) def quit_action_triggered(self): self.window.close() def play_button_clicked(self): self.music_player.play() def pause_button_clicked(self): self.music_player.pause() def stop_button_clicked(self): self.music_player.stop() def raise_volume_button_clicked(self): volume = self.music_player.volume() if volume != 100: volume = volume + 10 self.music_player.setVolume(volume) def lower_volume_button_clicked(self): volume = self.music_player.volume() if volume != 0: volume = volume - 10 self.music_player.setVolume(volume)
class SoundPlayer: def __init__(self, soundfile, parent): self.soundfile = soundfile self.isplaying = False self.time = 0 # current audio position in frames self.audio = QMediaPlayer() self.decoder = QAudioDecoder() self.is_loaded = False self.volume = 100 self.isplaying = False self.decoded_audio = {} self.only_samples = [] self.decoding_is_finished = False self.max_bits = 32768 # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works self.audio.durationChanged.connect(self.on_durationChanged) #self.decoder.finished.connect(self.decode_finished_signal) self.audio.setMedia(QUrl.fromLocalFile(soundfile)) #self.decoder.setSourceFilename(soundfile) # strangely inconsistent file-handling # It will hang here forever if we don't process the events. while not self.is_loaded: QCoreApplication.processEvents() time.sleep(0.1) #self.decode_audio() #self.np_data = np.array(self.only_samples) #self.np_data = np.abs(self.np_data / self.max_bits) # A simple normalisation, with this the samples should all be between 0 and 1 # for i in self.decoded_audio.items(): # self.only_samples.extend(i[1][0]) # t = [] # for i in self.only_samples: # if i != []: # t.append(i + -(min(self.only_samples))) # # t2 = [] # for i in t: # t2.append(i / max(t)) # self.only_samples = t2 #print(len(self.only_samples)) #print(self.max_bits) self.isvalid = True self.pydubfile = None if AudioSegment: if which("ffmpeg") is not None: AudioSegment.converter = which("ffmpeg") elif which("avconv") is not None: AudioSegment.converter = which("avconv") else: if platform.system() == "Windows": AudioSegment.converter = os.path.join(get_main_dir(), "ffmpeg.exe") #AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe" else: # TODO: Check if we have ffmpeg or avconv installed AudioSegment.converter = "ffmpeg" try: if AudioSegment: print(self.soundfile) self.pydubfile = AudioSegment.from_file(self.soundfile, format=os.path.splitext(self.soundfile)[1][1:]) else: self.wave_reference = wave.open(self.soundfile) self.isvalid = True except: traceback.print_exc() self.wave_reference = None self.isvalid = False #self.audio.play() def audioformat_to_datatype(self, audioformat): num_bits = audioformat.sampleSize() signed = audioformat.sampleType() self.max_bits = 2 ** int(num_bits) if signed == QAudioFormat.SampleType.UnSignedInt: return "uint" + str(num_bits) + "_t" elif signed == QAudioFormat.SampleType.SignedInt: self.max_bits = int(self.max_bits / 2) return "int" + str(num_bits) + "_t" def decode_audio(self): self.decoder.start() while not self.decoding_is_finished: QCoreApplication.processEvents() if self.decoder.bufferAvailable(): tempdata = self.decoder.read() # We use the Pointer Address to get a cffi Pointer to the data (hopefully) cast_data = self.audioformat_to_datatype(tempdata.format()) possible_data = ffi.cast("{1}[{0}]".format(tempdata.sampleCount(), cast_data), int(tempdata.constData())) current_sample_data = [] for i in possible_data: current_sample_data.append(int(ffi.cast(cast_data, i))) #x = int(ffi.cast("int16_t", possible_data[0])) self.only_samples.extend(current_sample_data) self.decoded_audio[self.decoder.position()] = [current_sample_data, len(possible_data), tempdata.byteCount(), tempdata.format()] def decode_finished_signal(self): self.decoding_is_finished = True def on_durationChanged(self, duration): print("Changed!") print(duration) self.is_loaded = True def get_audio_buffer(self, bufferdata): print(bufferdata) def IsValid(self): return self.isvalid def Duration(self): return self.audio.duration() / 1000.0 def GetRMSAmplitude(self, time, sampleDur): if AudioSegment: return self.pydubfile[time*1000.0:(time+sampleDur)*1000.0].rms else: startframe = int(round(time * self.wave_reference.getframerate())) samplelen = int(round(sampleDur * self.wave_reference.getframerate())) self.wave_reference.setpos(startframe) frame = self.wave_reference.readframes(samplelen) width = self.wave_reference.getsampwidth() return audioop.rms(frame, width) def is_playing(self): if self.audio.state() == QMediaPlayer.PlayingState: return True else: return False def set_cur_time(self, newtime): self.time = newtime * 1000.0 self.audio.setPosition(self.time) def stop(self): self.isplaying = False self.audio.stop() def current_time(self): self.time = self.audio.position() / 1000.0 return self.time def set_volume(self, newvolume): self.volume = newvolume self.audio.setVolume(self.volume) def play(self, arg): self.isplaying = True # TODO: We should be able to replace isplaying with queries to self.audio.state() self.audio.play() def play_segment(self, start, length): print("Playing Segment") if not self.isplaying: # otherwise this get's kinda echo-y self.isplaying = True self.audio.setPosition(start * 1000.0) self.audio.play() thread.start_new_thread(self._wait_for_segment_end, (start, length)) def _wait_for_segment_end(self, newstart, newlength): start = newstart * 1000.0 length = newlength * 1000.0 end = start + length print(start) print(length) print(end) while self.audio.position() < end: QCoreApplication.processEvents() print(self.audio.position()) time.sleep(0.001) self.audio.stop() self.isplaying = False
class SoundPlayer: def __init__(self, soundfile, parent): self.soundfile = soundfile self.isplaying = False self.time = 0 # current audio position in frames self.audio = QMediaPlayer() self.is_loaded = False self.volume = 100 self.isplaying = False self.max_bits = 32768 # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works self.audio.durationChanged.connect(self.on_durationChanged) # self.decoder.finished.connect(self.decode_finished_signal) self.audio.setMedia(QUrl.fromLocalFile(soundfile)) # self.decoder.setSourceFilename(soundfile) # strangely inconsistent file-handling # It will hang here forever if we don't process the events. self.audio_file = audioread.audio_open(self.soundfile) self.audio_data = [] for buf in self.audio_file: self.audio_data.extend( struct.unpack("<{}H".format(int(len(list(buf)) / 2)), buf)) print(self.audio_data) print(len(self.audio_data)) print(len(self.audio_data) / self.audio_file.samplerate) print(self.audio_file.duration) print(self.audio_file.channels) print("DATAEND") while not self.is_loaded: QCoreApplication.processEvents() time.sleep(0.1) self.isvalid = True self.pydubfile = None if AudioSegment: if which("ffmpeg") is not None: AudioSegment.converter = which("ffmpeg") elif which("avconv") is not None: AudioSegment.converter = which("avconv") else: if platform.system() == "Windows": AudioSegment.converter = os.path.join( get_main_dir(), "ffmpeg.exe") # AudioSegment.converter = os.path.dirname(os.path.realpath(__file__)) + "\\ffmpeg.exe" else: # TODO: Check if we have ffmpeg or avconv installed AudioSegment.converter = "ffmpeg" self.isvalid = True # self.audio.play() def on_durationChanged(self, duration): print("Changed!") print(duration) self.is_loaded = True def get_audio_buffer(self, bufferdata): print(bufferdata) def IsValid(self): return self.isvalid def Duration(self): return self.audio.duration() / 1000.0 def GetRMSAmplitude(self, time_pos, sample_dur): if AudioSegment: return self.pydubfile[time_pos * 1000.0:(time_pos + sample_dur) * 1000.0].rms else: if time_pos > 0: sample_pos = int(self.audio_file.samplerate * time_pos) else: sample_pos = 0 sample_end = int(sample_pos + sample_dur * self.audio_file.samplerate) return audioop.rms( struct.pack( "<{}H".format(len(self.audio_data[sample_pos:sample_end])), *self.audio_data[sample_pos:sample_end]), 2) def is_playing(self): if self.audio.state() == QMediaPlayer.PlayingState: return True else: return False def set_cur_time(self, newtime): self.time = newtime * 1000.0 self.audio.setPosition(self.time) def stop(self): self.isplaying = False self.audio.stop() def current_time(self): self.time = self.audio.position() / 1000.0 return self.time def set_volume(self, newvolume): self.volume = newvolume self.audio.setVolume(self.volume) def play(self, arg): self.isplaying = True # TODO: We should be able to replace isplaying with queries to self.audio.state() self.audio.play() def play_segment(self, start, length): print("Playing Segment") if not self.isplaying: # otherwise this get's kinda echo-y self.isplaying = True self.audio.setPosition(start * 1000.0) self.audio.play() thread.start_new_thread(self._wait_for_segment_end, (start, length)) def _wait_for_segment_end(self, newstart, newlength): start = newstart * 1000.0 length = newlength * 1000.0 end = start + length print(start) print(length) print(end) while self.audio.position() < end: if not self.isplaying: return 0 QCoreApplication.processEvents() print(self.audio.position()) time.sleep(0.001) self.audio.stop() self.isplaying = False
class Player(QWidget): media_loaded = Signal(str) stopped = Signal(str) playlist_size_changed = Signal(int) handle_double_click = Slot() def __init__(self, parent=None): super(Player, self).__init__(parent) self.duration = 0 self.volume = 50 self.player = QMediaPlayer() self.playlist = Playlist(self) self.videoWidget = VideoWidget() self.next_url = QUrl() self.context_menu = QMenu(self) self.display_splitter = QSplitter(Qt.Horizontal) self.repeat_control = RepeatControl(parent=self) self.repeat_control.get_player_position = self.player.position self.repeat_control.set_position_to_player = self.player.setPosition self.player.positionChanged.connect(self.repeat_control.set_pos) self.setAcceptDrops(True) std_icon = self.style().standardIcon self.play_button = create_flat_button(std_icon(QStyle.SP_MediaPlay)) self.stopButton = create_flat_button(std_icon(QStyle.SP_MediaStop), '') self.backwardButton = create_flat_button( std_icon(QStyle.SP_MediaSkipBackward), '') self.forwardButton = create_flat_button( std_icon(QStyle.SP_MediaSkipForward), '') self.order_list = self.repeat_control.menu() self.order_list.setFixedWidth(115) self.playback_rate_menu = QComboBox() self.playback_rate_menu.addItems( ('0.5x', '0.75x', '0.9x', '1.0x', '1.1x', '1.25x', '1.5x')) self.playback_rate_menu.setCurrentText('1.0x') self.muteButton = create_flat_button( std_icon(QStyle.SP_MediaVolume if not self.player.isMuted() else QStyle.SP_MediaVolumeMuted)) self.volumeBar = QSlider(Qt.Horizontal) self.volumeBar.setRange(0, 100) self.volumeBar.setValue(self.volume) self.labelVolume = QLabel(str(self.volume)) self.labelVolume.setMinimumWidth(24) self.statusInfoLabel = QLabel() self.seekBar = QSlider(Qt.Horizontal) self.seekBar.setRange(0, self.player.duration() / 1000) self.labelTotalTime = QLabel('00:00') self.labelCurrentTime = QLabel('00:00') self.create_layout() self.create_connections() self.player.setVideoOutput(self.videoWidget) self.videoWidget.show() def create_layout(self): seekBarLayout = QHBoxLayout() seekBarLayout.addWidget(self.labelCurrentTime) seekBarLayout.addWidget(self.seekBar) seekBarLayout.addWidget(self.labelTotalTime) controlWithoutSeekBarLayout = QHBoxLayout() controlWithoutSeekBarLayout.setSpacing(1) controlWithoutSeekBarLayout.addWidget(self.play_button) controlWithoutSeekBarLayout.addWidget(self.stopButton) controlWithoutSeekBarLayout.addWidget(self.backwardButton) controlWithoutSeekBarLayout.addWidget(self.forwardButton) controlWithoutSeekBarLayout.addWidget(self.order_list) controlWithoutSeekBarLayout.addWidget(self.playback_rate_menu) controlWithoutSeekBarLayout.addStretch(stretch=2) controlWithoutSeekBarLayout.addWidget(self.muteButton) controlWithoutSeekBarLayout.addWidget(self.volumeBar) controlWithoutSeekBarLayout.addWidget(self.labelVolume, alignment=Qt.AlignRight) controlLayout = QVBoxLayout() controlLayout.addLayout(seekBarLayout) controlLayout.addLayout(controlWithoutSeekBarLayout) self.display_splitter.setOpaqueResize(False) self.display_splitter.addWidget(self.videoWidget) self.display_splitter.addWidget(self.playlist.widget) self.display_splitter.setSizes([300, 200]) layout = QVBoxLayout() layout.setContentsMargins(11, 0, 11, 0) layout.addWidget(self.display_splitter, 1) layout.addLayout(controlLayout) layout.addWidget(self.repeat_control.ab_repeat_widget) layout.addWidget(self.statusInfoLabel) self.setLayout(layout) def create_connections(self): self.play_button.clicked.connect(self.optimal_play) self.stopButton.clicked.connect(self.stop) self.backwardButton.clicked.connect(self.skip_backward) self.forwardButton.clicked.connect(self.skip_forward) self.muteButton.clicked.connect(self.toggleMute) self.playback_rate_menu.currentTextChanged.connect( self.set_playback_rate) self.player.stateChanged.connect(self.playerStateChanged) self.player.mediaStatusChanged.connect(self.mediaStatusChanged) self.player.durationChanged.connect(self.durationChanged) self.player.positionChanged.connect(self.positionChanged) self.player.error.connect(self.handleError) self.volumeBar.sliderMoved.connect(self.setVolume) self.volumeBar.sliderReleased.connect(self.setVolume) self.volumeBar.valueChanged.connect(self.volumeChanged) self.seekBar.sliderMoved.connect(self.seek) self.seekBar.sliderReleased.connect(self.seekBarClicked) self.repeat_control.pos_exceeded.connect(self.seek) self.player.currentMediaChanged.connect(self.repeat_control.reset) self.playlist.double_clicked.connect(self.load_and_play) self.videoWidget.double_clicked.connect(self.no_future) def contextMenuEvent(self, event): self.context_menu.exec_(event.globalPos()) def read_settings(self): settings = QSettings() settings.beginGroup('player') self.order_list.setCurrentIndex(settings.value('order_list', 0)) self.display_splitter.restoreState( QByteArray(settings.value('splitter_sizes'))) settings.endGroup() self.playlist.read_settings() def no_future(self): self.display_splitter.moveSplitter(0, 1) def autoplay(self): """メディアを読み込み、再生する。 order_listに応じて、次に何を再生するかを決める。 """ i = self.order_list.currentIndex() if i == 1: # self.repeat_track() return elif i == 2: self.repeat_all() else: self.next_track() self.play() def optimal_play(self): if self.player.state() == QMediaPlayer.StoppedState: self.load_and_play() else: self.play() def load_and_play(self): self.load(self.playlist.get_new_one()) self.play() def load(self, file_url: QUrl): if file_url is None: return None if file_url.isValid(): c = QMediaContent(file_url) self.player.setMedia(c) self.media_loaded.emit(self.playlist.current_title()) self.enableInterface() def play(self): if self.player.state() == QMediaPlayer.PlayingState: self.player.pause() return if self.player.mediaStatus() == QMediaPlayer.LoadingMedia or\ self.player.mediaStatus() == QMediaPlayer.StalledMedia: QTimer.singleShot(600, self.player.play) self.player.play() self.playlist.update_listview() def stop(self): if not self.player.state() == QMediaPlayer.StoppedState: self.seek(0) self.player.stop() self.setStatusInfo('Stopped') self.stopped.emit('') def playerStateChanged(self, state): if state == QMediaPlayer.PlayingState: self.play_button.setIcon(self.style().standardIcon( QStyle.SP_MediaPause)) else: self.play_button.setIcon(self.style().standardIcon( QStyle.SP_MediaPlay)) def durationChanged(self, duration): self.repeat_control.set_duration(duration) duration /= 1000 self.duration = duration totalTime = QTime((duration / 3600) % 60, (duration / 60) % 60, (duration % 60), (duration * 1000) % 1000) format = 'hh:mm:ss' if duration > 3600 else 'mm:ss' totalTimeStr = totalTime.toString(format) self.labelTotalTime.setText(totalTimeStr) self.seekBar.setMaximum(duration) def positionChanged(self, progress): progress /= 1000 self.updateCurrentTime(progress) self.seekBar.setValue(progress) def updateCurrentTime(self, currentInfo): if currentInfo: currentTime = QTime((currentInfo / 3600) % 60, (currentInfo / 60) % 60, currentInfo % 60, (currentInfo * 1000) % 1000) format = 'hh:mm:ss' if self.duration > 3600 else 'mm:ss' currentTimeStr = currentTime.toString(format) else: currentTimeStr = '00:00' self.labelCurrentTime.setText(currentTimeStr) def repeat_track(self): QTimer.singleShot(50, self.play) def repeat_all(self): if self.playlist.count() - 1 == self.playlist.current_row(): url = self.playlist.first() self.load(url) else: self.next_track() def setVolume(self): self.player.setVolume(self.volumeBar.sliderPosition() * 2) def volumeChanged(self): self.labelVolume.setText(str(self.volumeBar.sliderPosition())) self.volume = self.volumeBar.sliderPosition() def seekBarClicked(self): self.seek(self.seekBar.sliderPosition()) def seek(self, seconds): self.player.setPosition(seconds * 1000) def set_playback_rate(self, rate_text): self.player.setPlaybackRate(float(rate_text[:-1])) def toggleMute(self): if self.player.isMuted(): self.player.setMuted(False) self.muteButton.setIcon(self.style().standardIcon( QStyle.SP_MediaVolume)) else: self.player.setMuted(True) self.muteButton.setIcon(self.style().standardIcon( QStyle.SP_MediaVolumeMuted)) def disableInterface(self): self.play_button.setEnabled(False) self.stopButton.setEnabled(False) self.backwardButton.setEnabled(False) self.forwardButton.setEnabled(False) self.labelCurrentTime.setText('00:00') self.labelTotalTime.setText('00:00') def enableInterface(self): self.play_button.setEnabled(True) self.stopButton.setEnabled(True) self.backwardButton.setEnabled(True) self.forwardButton.setEnabled(True) def mediaStatusChanged(self, status): if status == QMediaPlayer.LoadingMedia: self.setStatusInfo('Loading...') elif status == QMediaPlayer.BufferingMedia: self.setStatusInfo('Buffering') elif status == QMediaPlayer.EndOfMedia: # self.player.stop() self.autoplay() elif status == QMediaPlayer.InvalidMedia: self.handleError() #TODO: Step Forward を割り当てる def clearStatusInfo(self): self.statusInfoLabel.setText("") def handleError(self): self.disableInterface() self.setStatusInfo('Error: ' + self.player.errorString()) def setStatusInfo(self, message, seconds=5): if not message == '': self.statusInfoLabel.setText(message) QTimer.singleShot(seconds * 1000, self.clearStatusInfo) def next_track(self): url = self.playlist.next() if url is None: return None else: self.load(url) def previous_track(self): url = self.playlist.previous() if url is None: return None else: self.load(url) def skip_forward(self): self.next_track() self.play() def skip_backward(self): if self.seekBar.sliderPosition() > 2: self.seek(0) else: self.previous_track() self.play() def forward(self, seconds): currentPosition = self.seekBar.sliderPosition() if currentPosition + seconds < self.duration: self.seek(currentPosition + seconds) else: self.seek(self.duration - 1) def backward(self, seconds): self.forward(-seconds) def forward_short(self): self.forward(SeekStep.SHORT) def forward_medium(self): self.forward(SeekStep.MEDIUM) def forward_long(self): self.forward(SeekStep.LONG) def forward_verylong(self): self.forward(SeekStep.VERYLONG) def backward_short(self): self.backward(SeekStep.SHORT) def backward_medium(self): self.backward(SeekStep.MEDIUM) def backward_long(self): self.backward(SeekStep.LONG) def backward_verylong(self): self.backward(SeekStep.VERYLONG) def dragEnterEvent(self, event): if event.mimeData().hasUrls(): event.accept() def dragMoveEvent(self, event): if event.mimeData().hasUrls(): event.accept() def dropEvent(self, event): if event.mimeData().hasUrls(): urls = event.mimeData().urls() self.load(urls[0]) # self.stop() self.play()
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pbLecture.clicked.connect(self.lectureClicked) self.ui.pbPause.clicked.connect(self.pauseClicked) self.ui.pbStop.clicked.connect(self.stopClicked) self.ui.dVolume.valueChanged.connect(self.volumeChanged) self.ui.sTpsCourant.valueChanged.connect(self.sliderPositionChanged) self.ui.pbAjout.clicked.connect(self.ajouterMedia2) self.ui.pbSuppr.clicked.connect(self.supprMedia) self.ui.lPlaylist.itemDoubleClicked.connect(self.mediaSelected2) self.mediaPlayer = QMediaPlayer() self.mediaPlayer.setVideoOutput(self.ui.wVideo) self.mediaPlayer.durationChanged.connect(self.mediaDurationChanged) self.mediaPlayer.positionChanged.connect(self.mediaPositionChanged) self.ui.pbSuivant.clicked.connect(self.suivantClicked) self.ui.pbPrecedent.clicked.connect(self.precedentClicked) def lectureClicked(self): print("Lecture !!") self.mediaPlayer.play() def pauseClicked(self): print("Pause !!") if self.mediaPlayer.state() == QMediaPlayer.PausedState: self.mediaPlayer.play() elif self.mediaPlayer.state() == QMediaPlayer.PlayingState: self.mediaPlayer.pause() def stopClicked(self): self.mediaPlayer.stop() def volumeChanged(self): self.mediaPlayer.setVolume(self.ui.dVolume.value()) self.ui.lVolume.setText(str(self.ui.dVolume.value()) + "%") def mediaDurationChanged(self): print("mediaLoaded") self.ui.lTpsCourant.setText("00:00:00") mediaDuration = self.mediaPlayer.duration() self.ui.sTpsCourant.setRange(0, mediaDuration) ############### totalTimeMedia = QTime(0, 0, 0) totalTimeMedia = totalTimeMedia.addMSecs(mediaDuration) self.ui.lTpsTotal.setText(totalTimeMedia.toString("HH:mm:ss")) def mediaPositionChanged(self): self.ui.sTpsCourant.valueChanged.disconnect(self.sliderPositionChanged) mediaPosition = self.mediaPlayer.position() self.ui.sTpsCourant.setValue(mediaPosition) ############## currentTimeMedia = QTime(0, 0, 0) currentTimeMedia = currentTimeMedia.addMSecs(mediaPosition) self.ui.lTpsCourant.setText(currentTimeMedia.toString("HH:mm:ss")) self.ui.sTpsCourant.valueChanged.connect(self.sliderPositionChanged) def sliderPositionChanged(self): self.mediaPlayer.positionChanged.disconnect(self.mediaPositionChanged) self.mediaPlayer.setPosition(self.ui.sTpsCourant.value()) self.mediaPlayer.positionChanged.connect(self.mediaPositionChanged) def ajouterMedia(self): nomMedia = QFileDialog.getOpenFileName(self, "Choix Film", "c:/", "Movie Files (*.avi *.mp4)") item = QListWidgetItem(nomMedia[0]) self.ui.lPlaylist.addItem(item) def ajouterMedia2(self): nomMedia = QFileDialog.getOpenFileName(self, "Choix Film", "c:/", "Movie Files (*.avi *.mp4)") if nomMedia[0] == "": #si aucun fichier selectionné return fInfo = QFileInfo(nomMedia[0]) fShortName = fInfo.baseName() item = QListWidgetItem(fShortName) item.setToolTip(nomMedia[0]) self.ui.lPlaylist.addItem(item) def supprMedia(self): rowItem = self.ui.lPlaylist.currentRow() if rowItem != -1: self.ui.lPlaylist.takeItem(rowItem) def mediaSelected(self): currentItem = self.ui.lPlaylist.currentItem() mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.text())) self.mediaPlayer.setMedia(mediaContent) self.lectureClicked() def mediaSelected2(self): currentItem = self.ui.lPlaylist.currentItem() mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.toolTip())) self.mediaPlayer.setMedia(mediaContent) self.lectureClicked() def suivantClicked(self): currentItemRow = self.ui.lPlaylist.currentRow() if currentItemRow == -1: return totalItems = self.ui.lPlaylist.count() self.ui.lPlaylist.setCurrentRow((currentItemRow + 1) % totalItems) self.mediaSelected2() def precedentClicked(self): currentItemRow = self.ui.lPlaylist.currentRow() if currentItemRow == -1: return totalItems = self.ui.lPlaylist.count() self.ui.lPlaylist.setCurrentRow((currentItemRow - 1) % totalItems) self.mediaSelected2()
class MainWindow(QObject): #class constructor def __init__(self, ui_file, parent=None): #reference to our music player self.music_player = QMediaPlayer() self.music_player.setVolume(89) #call parent QObject constructor super(MainWindow, self).__init__(parent) #add background image """ self.title = "Adrian's boombox" self.MainWindow.setWindowTitle(self.title) label = QLabel(self) pixmap = QPixmap('MW_background.jfif') label.setPixmap(pixmap) self.setCentralWidget(label) self.resize(pixmap.width(), pixmap.height()) """ #load the UI file into Python ui_file = QFile(ui_file) ui_file.open(QFile.ReadOnly) loader = QUiLoader() self.window = loader.load(ui_file) #always remember to close files ui_file.close() #add event listeners open_action = self.window.findChild(QAction, 'action_open') open_action.triggered.connect(self.open_action_triggered) quit_action = self.window.findChild(QAction, 'action_quit') quit_action.triggered.connect(self.quit_action_triggered) play_button = self.window.findChild(QPushButton, 'play_button') play_button.clicked.connect(self.play_button_clicked) stop_button = self.window.findChild(QPushButton, 'stop_button') stop_button.clicked.connect(self.stop_button_clicked) volume_slider = self.window.findChild(QSlider, 'volume_slider') """ #volume_slider.setFocusPolicy(QSlider.StrongFocus) #volume_slider.clicked.connect(self.music_player.setVolume(15)) volume_slider.SliderToMaximum """ volume_slider.setTickInterval(10) volume_slider.setSingleStep(1) volume_slider.setTickPosition(QSlider.TicksBothSides) volume_slider.setMinimum(1) volume_slider.setMaximum(100) volume_slider.setValue(25) volume_slider.valueChanged.connect(self.volume_change) volume_plus = self.window.findChild(QPushButton, 'volume_plus') volume_plus.clicked.connect(self.volume_plus_button_clicked) volume_minus = self.window.findChild(QPushButton, 'volume_minus') volume_minus.clicked.connect(self.volume_minus_button_clicked) #show window to user self.window.show() def open_action_triggered(self): file_name = QFileDialog.getOpenFileName(self.window) self.music_player.setMedia(QUrl.fromLocalFile(file_name[0])) song_label = self.window.findChild(QLabel, 'song_playing_label') display_title = os.path.basename(str(file_name[0])) song_label.setText(display_title) def quit_action_triggered(self): self.window.close() def play_button_clicked(self): self.music_player.play() def stop_button_clicked(self): self.music_player.stop() def volume_plus_button_clicked(self): self.music_player.setVolume(100) def volume_minus_button_clicked(self): self.music_player.setVolume(0) def volume_change(self): print(self.window.volume_slider.value() ) # this prints volume of Qslider object #print(self.music_player.volume()) # this prints volume of music_player object self.music_player.setVolume(self.window.volume_slider.value())
class MainWindow(QMainWindow): """ Description ------------- The central window that is responsible for the user-interface for the Trivial Purfuit application """ def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.number_players = 0 self.board = Board() self.start_menu = StartMenu() self.setup_menu = SetupMenu() self.media_player = QMediaPlayer(None, QMediaPlayer.VideoSurface) self.connect(self.start_menu.ui.new_game_button, SIGNAL("clicked()"), self.setup_game) self.connect(self.start_menu.ui.cancel_button, SIGNAL("clicked()"), self.close_game) self.connect(self.setup_menu.ui.start_game_button, SIGNAL("clicked()"), self.start_game) self.connect(self.setup_menu.ui.exit_game_button, SIGNAL("clicked()"), self.close_game) self.connect(self.board.restart_menu.ui.leave_game_button, SIGNAL("clicked()"), self.close_game) self.connect(self.board.restart_menu.ui.play_again_button, SIGNAL("clicked()"), self.restart_game) self.start_menu.show() #self.music_thread = Thread(target=self.play_background_music) #self.music_thread.start() # end __init__() def play_background_music(self): self.media_player.setMedia( QUrl.fromLocalFile( definitions.ROOT_DIR + "/Trivial_Purfuit/resources/audio/bensound-anewbeginning.mp3")) self.media_player.setVolume(5) self.media_player.play() while True: print("State: ", self.media_player.state()) # end play_background_music def setup_game(self): """ Description ------------- - Function to configure/setup a new game """ self.start_menu.hide() self.setup_menu.show() # end setup_game() def start_game(self): """ Description ------------- - Function to start the game """ try: self.number_players = int( self.setup_menu.ui.players_text_edit.toPlainText()) pone_name = self.setup_menu.ui.playerOneNameTextEdit.toPlainText() ptwo_name = self.setup_menu.ui.playerTwoNameTextEdit.toPlainText() pthree_name = self.setup_menu.ui.playerThreeNameTextEdit.toPlainText( ) pfour_name = self.setup_menu.ui.playerFourNameTextEdit.toPlainText( ) self.board.initialize_player_tokens(self.number_players, pone_name, ptwo_name, pthree_name, pfour_name) self.setup_menu.hide() self.board.initialize_game() self.board.show() self.board.hide_dirs() # TODO: JGC self.board.board_menu.ui.player_order_group_box.hide() except ValueError: print("[ERROR] Invalid input! Must be (1, 2, 3, or 4)!") # end start_game() def close_game(self): """ Description ------------- - Terminate the Trivial Purfuit application """ #self.music_thread.join() QApplication.quit() # end close_game() def restart_game(self): self.board = Board() self.connect(self.board.restart_menu.ui.leave_game_button, SIGNAL("clicked()"), self.close_game) self.connect(self.board.restart_menu.ui.play_again_button, SIGNAL("clicked()"), self.restart_game) self.setup_menu.show()
class SoundPlayer: def __init__(self, soundfile, parent): self.soundfile = soundfile self.isplaying = False self.time = 0 # current audio position in frames self.audio = QMediaPlayer() self.decoder = QAudioDecoder() self.is_loaded = False self.volume = 100 self.isplaying = False self.decoded_audio = {} self.only_samples = [] self.decoding_is_finished = False self.max_bits = 32768 self.signed = False # File Loading is Asynchronous, so we need to be creative here, doesn't need to be duration but it works self.audio.durationChanged.connect(self.on_durationChanged) self.decoder.finished.connect(self.decode_finished_signal) self.audio.setMedia(QUrl.fromLocalFile(soundfile)) self.decoder.setSourceFilename( soundfile) # strangely inconsistent file-handling self.top_level_widget = None for widget in QtWidgets.QApplication.topLevelWidgets(): if "lip_sync_frame" in dir(widget): self.top_level_widget = widget self.top_level_widget.lip_sync_frame.status_progress.show() self.top_level_widget.lip_sync_frame.status_progress.reset() self.top_level_widget.lip_sync_frame.status_progress.setMinimum(0) self.top_level_widget.lip_sync_frame.status_progress.setMaximum(0) # It will hang here forever if we don't process the events. while not self.is_loaded: QCoreApplication.processEvents() time.sleep(0.01) self.top_level_widget.lip_sync_frame.status_progress.setMaximum( self.decoder.duration()) self.decode_audio( self.top_level_widget.lip_sync_frame.status_bar_progress) self.top_level_widget.lip_sync_frame.status_progress.hide() self.np_data = np.array(self.only_samples) if not self.signed: # don't ask me why this fixes 8 bit samples... self.np_data = self.np_data - self.max_bits / 2 print(len(self.only_samples)) print(self.max_bits) self.isvalid = True def audioformat_to_datatype(self, audioformat): num_bits = audioformat.sampleSize() signed = audioformat.sampleType() self.max_bits = 2**int(num_bits) if signed == QAudioFormat.SampleType.UnSignedInt: self.signed = False return "uint{0}_t".format(str(num_bits)) elif signed == QAudioFormat.SampleType.SignedInt: self.signed = True self.max_bits = int(self.max_bits / 2) return "int{0}_t".format(str(num_bits)) def decode_audio(self, progress_callback): self.decoder.start() while not self.decoding_is_finished: QCoreApplication.processEvents() if self.decoder.bufferAvailable(): tempdata = self.decoder.read() # We use the Pointer Address to get a cffi Pointer to the data (hopefully) cast_data = self.audioformat_to_datatype(tempdata.format()) possible_data = ffi.cast( "{1}[{0}]".format(tempdata.sampleCount(), cast_data), int(tempdata.constData())) self.only_samples.extend(possible_data) self.decoded_audio[self.decoder.position()] = [ possible_data, len(possible_data), tempdata.byteCount(), tempdata.format() ] progress_callback(self.decoder.position()) def decode_finished_signal(self): self.decoding_is_finished = True def on_durationChanged(self, duration): self.is_loaded = True def get_audio_buffer(self, bufferdata): print(bufferdata) def IsValid(self): return self.isvalid def Duration(self): return self.audio.duration() / 1000.0 def GetRMSAmplitude(self, time_pos, sample_dur): # time_start = time_pos * (len(self.only_samples)/self.Duration()) # time_end = (time_pos + sample_dur) * (len(self.only_samples)/self.Duration()) # samples = self.only_samples[int(time_start):int(time_end)] time_start = time_pos * (len(self.np_data) / self.Duration()) time_end = (time_pos + sample_dur) * (len(self.np_data) / self.Duration()) samples = self.np_data[int(time_start):int(time_end)] if len(samples): return np.sqrt(np.mean(samples**2)) else: return 1 def is_playing(self): if self.audio.state() == QMediaPlayer.PlayingState: return True else: return False def set_cur_time(self, newtime): self.time = newtime * 1000.0 self.audio.setPosition(self.time) def stop(self): self.isplaying = False self.audio.stop() def current_time(self): self.time = self.audio.position() / 1000.0 return self.time def set_volume(self, newvolume): self.volume = newvolume self.audio.setVolume(self.volume) def play(self, arg): self.isplaying = True # TODO: We should be able to replace isplaying with queries to self.audio.state() self.audio.play() def play_segment(self, start, length): if not self.is_playing(): # otherwise this get's kinda echo-y self.isplaying = True self.audio.setPosition(start * 1000.0) self.audio.play() thread.start_new_thread(self._wait_for_segment_end, (start, length)) def _wait_for_segment_end(self, newstart, newlength): start = newstart * 1000.0 length = newlength * 1000.0 end = start + length while self.audio.position() < end: if not self.isplaying: return 0 QCoreApplication.processEvents() time.sleep(0.001) self.audio.stop() self.isplaying = False
class VedioUI(QWidget): def __init__(self): super(VedioUI, self).__init__() #定义视频总时长(分钟/秒钟),当前播放到的时间(单位ms) self.vedio_duration_total = '00:00' self.vedio_duration_now = 0 #定义窗口和播放器 self.player = QMediaPlayer(self) self.video_widget = myQVideoWidget() self.video_widget.resize(self.width(), self.height()) self.player.setVideoOutput(self.video_widget) #设置按钮 self.start_pause_btn = QPushButton(self) self.stop_btn = QPushButton(self) self.fast_btn = QPushButton(self) self.back_btn = QPushButton(self) self.screenshot_btn = QPushButton(self) #设定时间块 self.time_label = QLabel(self) self.time_label.setText('--/--') self.progress_slider = QSlider(self) self.progress_slider.setEnabled(False) #没有视频播放时,进度条不可使用 self.progress_slider.setOrientation(Qt.Horizontal) #进度条移动事件 self.progress_slider.sliderMoved.connect(self.move_position) #设定图标 self.start_pause_btn.setIcon(QIcon('ico/pause.png')) self.stop_btn.setIcon(QIcon('ico/stop.png')) self.fast_btn.setIcon(QIcon('ico/fast_forward.png')) self.back_btn.setIcon(QIcon('ico/back_forward.png')) self.screenshot_btn.setIcon(QIcon('ico/screenshot.png')) #点击链接 self.start_pause_btn.clicked.connect( lambda: self.btn_func(self.start_pause_btn)) self.stop_btn.clicked.connect(lambda: self.btn_func(self.stop_btn)) self.fast_btn.clicked.connect(lambda: self.btn_func(self.fast_btn)) self.back_btn.clicked.connect(lambda: self.btn_func(self.back_btn)) self.screenshot_btn.clicked.connect( lambda: self.btn_func(self.screenshot_btn)) #获取视频时间 self.player.durationChanged.connect(self.get_duration) #更新进度条 self.player.positionChanged.connect(self.update_position) #界面布局 self.h1_layout = QHBoxLayout() self.h2_layout = QHBoxLayout() self.v_layout = QVBoxLayout() self.h1_layout.addWidget(self.progress_slider) self.h1_layout.addWidget(self.time_label) self.h2_layout.addWidget(self.back_btn) self.h2_layout.addWidget(self.start_pause_btn) self.h2_layout.addWidget(self.stop_btn) self.h2_layout.addWidget(self.fast_btn) self.h2_layout.addWidget(self.screenshot_btn) self.v_layout.addWidget(self.video_widget) self.v_layout.addLayout(self.h1_layout) self.v_layout.addLayout(self.h2_layout) self.v_layout.setStretch(0, 1) self.setLayout(self.v_layout) #设定窗口名称及大小 self.setWindowTitle("视频播放") self.resize(1024, 768) #居中显示 self.center() #文件加载与播放 def vedio_show(self, vedio_dir=None): if vedio_dir: #添加播放文件 self.media_content = QMediaContent(QUrl.fromLocalFile(vedio_dir)) self.player.setMedia(self.media_content) #声音 self.player.setVolume(50) #开始播放 self.player.play() else: QMessageBox.critical(self,'文件打开失败',\ '1.文件扩展名与文件类型不匹配!\n2.路径中请勿含有中文字符!\n3.文件损坏!\n4.文件无法读取!') exit(-1) #按键链接 def btn_func(self, btn): pass if btn == self.start_pause_btn: # 0停止状态 1正在播放 2暂停状态 if self.player.state() == 1: self.player.pause() self.start_pause_btn.setIcon(QIcon('ico/start.png')) else: self.player.play() self.start_pause_btn.setIcon(QIcon('ico/pause.png')) # elif btn == self.stop_btn: # elif btn == self.fast_btn: # elif btn == self.back_btn: elif btn == self.screenshot_btn: self.player.pause() self.start_pause_btn.setIcon(QIcon('ico/start.png')) QMessageBox.information(self, "提示", '请框取集装箱编号区域') #鼠标修改 self.video_widget.setCursor(Qt.CrossCursor) self.video_widget.select_on() #让屏幕居中 def center(self): #获取屏幕坐标系 screen = QDesktopWidget().screenGeometry() #获取窗口坐标系 size = self.geometry() newLeft = (screen.width() - size.width()) / 2 newTop = (screen.height() - size.height()) / 2 self.move(newLeft, newTop) #将ms转化成 分钟:秒钟 def time_conversion(self, d): seconds = int(d / 1000) minutes = int(seconds / 60) seconds -= minutes * 60 return '{}:{}'.format(minutes, seconds) #设置QLable的时间 def time_set(self, d_now='00:00', d_total='00:00'): if d_now == '00:00': self.time_label.setText('--/--') self.start_pause_btn.setIcon(QIcon('ico/start.png')) else: self.time_label.setText(d_now + '/' + d_total) #获取视频总时长,并设定进度条可用 def get_duration(self, p): self.progress_slider.setRange(0, p) self.vedio_duration_total = self.time_conversion(p) self.progress_slider.setEnabled(True) #更新进度条和时间 def update_position(self, p): self.progress_slider.setValue(p) self.vedio_duration_now = p self.time_set(self.time_conversion(self.vedio_duration_now), self.vedio_duration_total) #移动滑块后更新视频,更新时间显示 def move_position(self, p): self.player.setPosition(p) self.vedio_duration_now = p self.time_set(self.time_conversion(self.vedio_duration_now), self.vedio_duration_total)
class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setFixedSize(400, 100) self.setWindowTitle("PyPRad") # Icon made by https://www.flaticon.com/authors/freepik self.setWindowIcon(QIcon("icon.png")) self.setWindowIconText("PyPRad") self.current_stream = "https://kathy.torontocast.com:3060/stream" # Add a Stream URL. Default URL # Setup Media Player self.player = QMediaPlayer(self, QMediaPlayer.StreamPlayback) self.player.setMedia(QUrl(self.current_stream)) # Connect Button connect_btn = QPushButton("Connect To Stream") connect_btn.setFixedWidth(150) connect_btn.clicked.connect(self.connectStream) # Play Button self.play = QPushButton() self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.play.setFixedWidth(100) self.play.clicked.connect(self.playStream) # Volume Slider slider = QSlider(Qt.Horizontal) slider.setRange(0, 100) slider.setFixedWidth(100) slider.setValue(100) slider.valueChanged.connect(self.setVolume) # Horizontal Layout hbox_layout = QHBoxLayout() hbox_layout.setContentsMargins(0, 0, 0, 0) hbox_layout.addWidget(connect_btn) hbox_layout.addWidget(self.play) hbox_layout.addWidget(slider) widget = QWidget() widget.setLayout(hbox_layout) self.player.stateChanged.connect(self.mediaStateChanged) self.setCentralWidget(widget) def connectStream(self): dlg = QInputDialog(self) dlg.setInputMode(QInputDialog.TextInput) dlg.setLabelText("URL:") dlg.setTextEchoMode(QLineEdit.Normal) dlg.setTextValue(self.current_stream) dlg.resize(400, 100) dlg.exec() if dlg.result() and validators.url( dlg.textValue()) and dlg.textValue() != self.current_stream: self.current_stream = dlg.textValue() self.player.setMedia(QUrl(self.current_stream)) elif dlg.result() and not validators.url(dlg.textValue()): msg_box = QMessageBox() msg_box.setText("Error URL. Please try again") msg_box.setWindowTitle("Error URL") msg_box.exec() self.connectStream() def playStream(self): if self.player.state() == QMediaPlayer.PlayingState: self.player.pause() else: self.player.play() def mediaStateChanged(self, state): if self.player.state() == QMediaPlayer.PlayingState: self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPause)) else: self.play.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) def setVolume(self, volume): self.player.setVolume(volume)