def __init__(self): super(App, self).__init__() self.setupUi(self) self.errorLabel = QtWidgets.QMessageBox self.mediaPlayer = Media.QMediaPlayer(None, Media.QMediaPlayer.VideoSurface) self.mediaPlayer.setVideoOutput(self.VideoPlayer) self.pathToFile = None self.pathToCSV = None self.pausedPosition = 0 self.currentVideoDuration = 0 self.heatMapIndex = None self.tsDevice = None self.mediaControl = Media.QMediaControl(self.mediaPlayer) self.mediaPlayer.setNotifyInterval(500) self.PlayButton.clicked.connect(self.play) self.PauseButton.clicked.connect(self.pause) self.StopButton.clicked.connect(self.stop) self.actionAdd_video.triggered.connect(self.addVideo) self.actionAdd_heatmap.triggered.connect(self.addHeatMap) self.mediaPlayer.durationChanged.connect(self.durationChanged) self.mediaPlayer.positionChanged.connect(self.positionChanged) self.mediaPlayer.error.connect(self.handleError) self.ProgressBar.sliderReleased.connect(self.progressBarValueChange)
def __init__(self, frame_action=None, finish_action=None, **kwargs): super(VideoPlayerWidget, self).__init__(**kwargs) if frame_action is None: self.frame_action = self.default_frame else: self.frame_action = frame_action if finish_action is None: self.finish_action = self.default_finish else: self.finish_action = finish_action self.ui = Ui_EmotionVideoPlayer() self.ui.setupUi(self) self.backgroundPalette = QtGui.QPalette() self.backgroundPalette.setColor(QtGui.QPalette.Background, QtGui.QColor(0, 0, 0)) self.setAutoFillBackground(True) self.setPalette(self.backgroundPalette) self.ui.videoPlayer = QtMultimediaWidgets.QVideoWidget() self.ui.gridLayout.addWidget(self.ui.videoPlayer, 1, 1, 1, 1) self.mediaPlayer = QtMultimedia.QMediaPlayer( self, QtMultimedia.QMediaPlayer.VideoSurface) self.video_item = QtMultimediaWidgets.QGraphicsVideoItem() self.mediaPlayer.setVideoOutput(self.ui.videoPlayer) self.mediaPlayer.mediaStatusChanged.connect(self.status_check) self.frameProbe = QtMultimedia.QVideoProbe(self) # self.frameProbe.videoFrameProbed.connect(self.frame) self.frameProbe.setSource(self.mediaPlayer) self.frame_number = 0 self.video = None
def __init__(self): self.view = PlayerWindow() self.playlist = QtMultimedia.QMediaPlaylist() self.player = QtMultimedia.QMediaPlayer() self.player.setPlaylist(self.playlist) self.progress_bar_pressed = False self.last_volume = None self.connect()
def set_file(self, url): if url.scheme() == '': url.setScheme('file') self.label.setText(url.fileName()) content = qtmm.QMediaContent(url) # self.player.setMedia(content) self.playlist = qtmm.QMediaPlaylist() self.playlist.addMedia(content) self.playlist.setCurrentIndex(1) self.player.setPlaylist(self.playlist) self.loop_cb.setChecked(False)
def __init__(self): super().__init__() self.setLayout(qtw.QGridLayout()) self.label = qtw.QLabel('No file loaded') self.layout().addWidget(self.label, 0, 0, 1, 2) self.play_button = PlayButton() self.layout().addWidget(self.play_button, 3, 0, 1, 2) self.player = qtmm.QMediaPlayer() self.play_button.clicked.connect(self.on_playbutton) self.player.stateChanged.connect(self.play_button.on_state_changed) self.file_button = qtw.QPushButton('Load File') self.file_button.clicked.connect(self.get_file) self.layout().addWidget(self.file_button, 4, 0) self.position = qtw.QSlider() self.position.setMinimum(0) self.position.setOrientation(qtc.Qt.Horizontal) self.layout().addWidget(self.position, 1, 0, 1, 2) self.player.positionChanged.connect(self.position.setSliderPosition) self.player.durationChanged.connect(self.position.setMaximum) self.position.sliderMoved.connect(self.player.setPosition) self.loop_cb = qtw.QCheckBox('Loop') self.loop_cb.stateChanged.connect(self.on_loop_cb) self.layout().addWidget(self.loop_cb, 2, 0) self.volume = qtw.QSlider() self.volume.setMinimum(0) self.volume.setMaximum(100) self.volume.setSliderPosition(75) self.volume.setOrientation(qtc.Qt.Horizontal) self.volume.sliderMoved.connect(self.player.setVolume) self.layout().addWidget(self.volume, 2, 1) self.recorder = qtmm.QAudioRecorder() # self.recorder.setAudioInput('default:') # sample_path = qtc.QDir.home().filePath('sample1') # self.recorder.setOutputLocation(qtc.QUrl.fromLocalFile(sample_path)) # self.recorder.setContainerFormat('audio/x-wav') # settings = qtmm.QAudioEncoderSettings() # settings.setCodec('audio/pcm') # settings.setSampleRate(44100) # settings.setQuality(qtmm.QMultimedia.HighQuality) # self.recorder.setEncodingSettings(settings) self.record_button = RecordButton() self.recorder.stateChanged.connect(self.record_button.on_state_changed) self.layout().addWidget(self.record_button, 4, 1) self.record_button.clicked.connect(self.on_recordbutton)
def __init__(self) -> None: super().__init__() self.player = QtMultimedia.QMediaPlayer() self.playlist = QtMultimedia.QMediaPlaylist() self.musics: List[MusicEntry] = list() self.currentIndex = -1 self.playbackMode = MyPlaylist.PlaybackMode.LOOP self.playing = False self.player.positionChanged.connect(self.positionChanged.emit) self.player.durationChanged.connect(self.durationChanged.emit) self.player.stateChanged.connect(self.onPlayerStateChanged) self.history: Dict[int, int] = dict() self.historyIndex = -1
def play(self): if self.pathToCSV is None: self.addHeatMap() if self.pathToFile is None: self.addVideo() self.video = Media.QMediaContent(QtCore.QUrl.fromLocalFile(self.pathToFile)) self.mediaPlayer.setMedia(self.video) else: self.video = Media.QMediaContent(QtCore.QUrl.fromLocalFile(self.pathToFile)) self.mediaPlayer.setMedia(self.video) self.mediaPlayer.setPosition(self.pausedPosition) self.mediaPlayer.play()
def __init__(self, parent=None, num_decimals=2, bw_delta_secs=1, fw_delta_secs=1): """ """ self.num_decimals = num_decimals self.bw_delta_secs = bw_delta_secs self.fw_delta_secs = fw_delta_secs # super().__init__(parent) # self.play_icon = self.style().standardIcon( QtWidgets.QStyle.SP_MediaPlay) self.pause_icon = self.style().standardIcon( QtWidgets.QStyle.SP_MediaPause) self.stop_icon = self.style().standardIcon( QtWidgets.QStyle.SP_MediaStop) self.bw_icon = self.style().standardIcon( QtWidgets.QStyle.SP_MediaSeekBackward) self.fw_icon = self.style().standardIcon( QtWidgets.QStyle.SP_MediaSeekForward) # first create player, then setup GUI, finally connect player to GUI self.media_player = QtMultimedia.QMediaPlayer(parent=self) self.media_player.setAudioRole(QtMultimedia.QAudio.MusicRole) # audio probe provides "real-time" readings from the source (the player) self.probe = QtMultimedia.QAudioProbe(parent=self) self.probe.setSource(self.media_player) self.probe.audioBufferProbed.connect(self.on_audio_probe) # self._setup_gui() self.media_player.stateChanged.connect(self.on_media_state_changed) # self.media_player.positionChanged.connect(self.on_pos_player_update) self.media_player.positionChanged.connect( lambda pos: self.on_pos_update(pos, "player")) self.media_player.error.connect(self.on_media_error) # this is needed to break the slider<->player update loop self._block_slider_player_loop = False # initialize with disabled buttons and zero range self.configure_gui(min_val=0, max_val=0, step=0.1, pos_secs=0, enable_buttons=False) # call this function to set the play/pause icon to media_player state self.on_media_state_changed() self.vol_s.setValue(50) # also initialize volume # self.current_qstream = None
def soundPlay(self, sound_name): path = dir_mix(Space["root"], path_read(self.sound_Actions[sound_name]["path"])) url = QtCore.QUrl.fromLocalFile(path) self.sound.setMedia(QtMultimedia.QMediaContent(url)) self.sound.play()
def load(self, path): fullpath = QtCore.QDir.current().absoluteFilePath(path) mediaContent = QtMultimedia.QMediaContent( QtCore.QUrl.fromLocalFile(fullpath)) self.content = QtMultimedia.QMediaPlayer(stage.canvasWidget) self.content._mediaStatusChangedSlot = lambda status: self._onMediaStatusChanged( status) self.content.mediaStatusChanged.connect( self.content._mediaStatusChangedSlot) self.content._errorSlot = lambda err: self_onError(err) self.content.error.connect(self.content._errorSlot) self.content.setMedia(mediaContent) self.content.stop()
def add_files(self,paths,playlist_name): print("addint to ",playlist_name) paths = [path for path in paths]; for path in paths: break; print(path, playlist_name) saving_playlist = True saving_to_library = False; if playlist_name == "Library": saving_playlist = False; saving_to_library = True else : self.add_files(paths,"Library") if playlist_name == "Now Playing": saving_playlist = False; cur_playlist = self._playlists[playlist_name] cur_playlist_mdata = self._playlists_mdata[playlist_name] for path in paths: mdata = AudioMetadata(path) if not saving_to_library or path not in self._library_set: n_media = QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(path)); cur_playlist.addMedia(n_media) cur_playlist_mdata.append(mdata); if saving_to_library : self._library_set.add(path); mdata.dbase_id = self.add_song_to_database(mdata); if saving_playlist: self.add_song_to_database_playlist(mdata,cur_playlist); if saving_playlist: self.database_con.commit(); print("finished adding to ",playlist_name) self.playlistUpdated.emit(playlist_name);
def __init__(self): super().__init__() self.setStyleSheet("QWidget { background-color: black }") self.setFixedSize(Snake.BOARD_WIDTH, Snake.BOARD_HEIGHT) self.game_active = True self.timer = QtCore.QBasicTimer() self.direction = Snake.RIGHT # each tuple (x, y) corresponds to the top left corner of the block (circle) self.snake_coords = deque() self.snake_coords.append((Snake.BLOCK_SIZE * Snake.NUM_BLOCKS_X // 2, Snake.BLOCK_SIZE * Snake.NUM_BLOCKS_Y // 2)) self.food = None self.new_food() self.score_sound = QtMultimedia.QSound("score.wav") self.start_button = QtWidgets.QPushButton("Start", self) self.start_button.setStyleSheet("QWidget { background-color: white }") self.start_button.move(self.geometry().center() - self.start_button.geometry().center()) self.start_button.clicked.connect(self.start_game) self.game_over_label = QtWidgets.QLabel("Game Over...", self) self.game_over_label.setStyleSheet("QLabel {color: yellow; font: 36pt}") self.game_over_label.setAttribute(QtCore.Qt.WA_TranslucentBackground) self.game_over_label.adjustSize() self.game_over_label.move((self.width() - self.game_over_label.width()) // 2, 0) self.game_over_label.hide() self.setWindowTitle("Snake game") self.show()
def _doPlayMusicAtIndex(self, index: int) -> None: self._logger.info("Do play music at index: %d", index) assert index >= 0 playlist = self.getCurrentPlaylist().orElseThrow(AssertionError) music = playlist.musics[index] self._logger.info("Prepare to play music %s : %s", music.artist, music.title) self._logger.info("Stop current playing if exist") self._proxy.stop() self._logger.info("Current playing stopped") self._logger.info("Set music content: %s", music.filename) self._proxy.blockSignals(True) self._proxy.setMedia(QtMultimedia.QMediaContent( QtCore.QUrl.fromLocalFile(music.filename)), realDuration=music.duration) self._sampleWidth = 0 self._samples = array.array("i") threading.Thread(target=self._setupSamples, args=(music.filename, )).start() self._proxy.blockSignals(False) self._logger.info("Music content set to player.") self._logger.info("Update current music index") self.setCurrentMusicIndex(index) self._logger.info("Now start to play music...") self._proxy.play() self._logger.info("Music play started.") self._playedCount += 1 self._logger.info("Played count now: %d", self._playedCount)
def img_capture(self): # Function for capture image. image_capture = QtMultimedia.QCameraImageCapture(self.camera) image_capture.setCaptureDestination( # Modes and Destination. QtMultimedia.QCameraImageCapture.CaptureToFile) self.camera.setCaptureMode(QtMultimedia.QCamera.CaptureStillImage) filename = os.path.dirname(os.path.abspath(__file__)) camera_path = os.path.join(filename, "camera/captures/") image_capture.capture(os.path.normpath(camera_path))
def startPlayWidget(self): self.SelectWidget = ModuleSelectorWidget("Play", self) self.setWindowTitle("Scales - Play: Select") self.setCentralWidget(self.SelectWidget) self.ToolBar.setVisible(True) sound = QtMultimedia.QSound("sounds/blip1.wav") sound.play() self.show()
def set_video(self, video): self.video = video if isinstance(video, pathlib.Path) or isinstance(video, str): video = QtCore.QUrl.fromLocalFile(str(video)) if isinstance(video, QtCore.QUrl): video = QtMultimedia.QMediaContent(video) self.mediaPlayer.setMedia(video) self.frame_number = 0
def main(): # useGUI = not '-no-gui' in sys.argv # app = QtWidgets.QApplication.activeWindow() if useGUI else QtCore.QCoreApplication(sys.argv) # app.show() player = QtMultimedia.QMediaPlayer() player.setMedia(QUrl.fromLocalFile("D:/SampleData/albamonSample.mp4")) player.setVideoOutput
def camera_check(self): cameras = qtmm.QCameraInfo.availableCameras() if not cameras: qtw.QMessageBox.critical( self, 'No cameras', 'No cameras were found, recording disabled.') else: return qtmm.QCamera(cameras[0])
def get_format(rate, wave): format = QtMultimedia.QAudioFormat() format.setChannelCount(wave.shape[1]) format.setSampleRate(rate) format.setSampleSize(16) format.setCodec("audio/pcm") format.setSampleType(QtMultimedia.QAudioFormat.SignedInt) return format
def load_directory(self, song_dir): home = pathlib.Path(song_dir) files = (element for element in home.iterdir() if element.is_file() and element.name.endswith(".mp3")) for fake_id, file in enumerate(files): url = QtCore.QUrl(file.as_posix()) media = QtMultimedia.QMediaContent(url) self.playlist.addMedia(media) print(f"{self.playlist.mediaCount()}") MockDomain.Generate(song_dir)
def add_playlist(self,name): print('adding playlist',name); if name in self._playlists : print("can't add that playlist") return False self._playlists_mdata[name] = []; new_playlist = QtMultimedia.QMediaPlaylist() self._playlists[name] = new_playlist; new_playlist.dbase_id = self.add_playlist_to_database(name); print('added playlsit' , name); self.playlistAdded.emit(name);
def __init__(self, parent, target=defaults.DEFAULT_INPUT): super(Microphone, self).__init__(parent) self.target = target settings = QtMultimedia.QAudioEncoderSettings() settings.setCodec('audio/x-raw') settings.setChannelCount(1) settings.setSampleRate(16000) settings.setEncodingOption('pcm-format', 's16le') self.setEncodingSettings(settings) self.connect(self, SIGNAL('availableAudioInputsChanged()'), self.on_inputs_changed)
def backAction(self): sound = QtMultimedia.QSound("sounds/blip1.wav") sound.play() curr_class = str(type(self.centralWidget())) #print(curr_class) #For Debugging Purposes if (curr_class == "<class 'PlayModule.PlayWidget'>"): self.startPlayWidget() elif (curr_class == "<class 'LearnModule.LearnWidget'>"): self.startLearnWidget() else: #Default to main menu self.startHomeWidget()
def __init__(self, parent=None, max_allowed_secs=600): """ """ super().__init__(parent) self.setWindowTitle(self.WINDOW_TITLE) self.max_allowed_secs = max_allowed_secs # self.audio_recorder = QtMultimedia.QAudioRecorder(self) self.audio_recorder.durationChanged.connect(self.on_duration_changed) self.audio_recorder.statusChanged.connect(self.on_status_changed) # self.audio_recorder.stateChanged.connect(self.on_state_changed) # self.audio_probe = QtMultimedia.QAudioProbe(self) self.audio_probe.setSource(self.audio_recorder) self.audio_probe.audioBufferProbed.connect(self.on_audio_probe) # self._setup_gui() # self.vol_s.setValue(100) self.result = [] self.sample_rate = -1
def init(self): self.database_con , self.database_cur = setup_database(); self._playback_rate = 1.0 self._repeating = False self._shuffled = False self._playlists_mdata = {} # mdata = meta data self._playlists = {} self._current_playlist = None; self._current_playlist_mdata = None; self._current_playlist_name = None; self._library = QtMultimedia.QMediaPlaylist(); self._library_set = set() self._playlists["Library"] = self._library self._playlists_mdata["Library"] = [] self._playlists["Now Playing"] = QtMultimedia.QMediaPlaylist() self._playlists_mdata["Now Playing"] = [] #it's first signal will be emitted later in read_from_database self.player = QtMultimedia.QMediaPlayer(self) self.player.setVolume(50);
def _make_output(self, output_info, data, volume): output = QtMultimedia.QAudioOutput(output_info, output_info.preferredFormat()) output.setVolume(volume) output.stateChanged.connect(lambda: self._delete_output(output)) buffer = QtCore.QBuffer() buffer.open(QtCore.QIODevice.ReadWrite) buffer.write(data) buffer.seek(0) output.start(buffer) return output
def Generate(cls, song_dir): song_dir = pathlib.Path(song_dir) files = (file for file in song_dir.iterdir() if file.is_file() and file.name.endswith((".ogg", ".mp3"))) for file in files: url = QtCore.QUrl(file.as_posix()) media = QtMultimedia.QMediaContent(url) meta = mutagen.File(file.as_posix()) # probe = FFProbe(file) cls.data.append(MockRecord(meta, file))
def create_widgets(self): self.video_widget = QtMultimediaWidgets.QVideoWidget() self.player = QtMultimedia.QMediaPlayer() self.toolbar = QtWidgets.QToolBar() self.file_menu = self.menuBar().addMenu("Fichier") # ACTIONS self.act_open = self.file_menu.addAction(self.open_icon, "Ouvrir") self.act_open.setShortcut("Ctrl+O") self.act_play = self.toolbar.addAction(self.play_icon, "Lire") self.act_previous = self.toolbar.addAction(self.previous_icon, "Revenir au début") self.act_pause = self.toolbar.addAction(self.pause_icon, "Pause") self.act_stop = self.toolbar.addAction(self.stop_icon, "Stop")
def operate(self): wrong = False try: if (self.operand == "+"): wrong = (int(self.numLeft.text()) + int(self.numRight.text())) != int( self.TextInput.text()) elif (self.operand == "-"): wrong = (int(self.numLeft.text()) - int(self.numRight.text())) != int( self.TextInput.text()) elif (self.operand == "*"): wrong = (int(self.numLeft.text()) * int(self.numRight.text())) != int( self.TextInput.text()) elif (self.operand == "/"): wrong = (int( int(self.numLeft.text()) / int(self.numRight.text()))) != int(self.TextInput.text()) except ValueError: sound = QtMultimedia.QSound("sounds/wrong.wav") sound.play() self.showMessageBox( "Invalid input. Please use numerical characters to input integers." ) return if (wrong): sound = QtMultimedia.QSound("sounds/wrong.wav") sound.play() self.showMessageBox("Incorrect, please try again.") else: sound = QtMultimedia.QSound("sounds/correct.wav") sound.play() self.showMessageBox("Nice job! You got it!") self.TextInput.clear() self.shuffle()
def show_pronunciation_to_writing_dialog(pronunciation, audio_file, callback): dialog = EphemeralDialog() possible_fonts = qg.QFontDatabase().families(qg.QFontDatabase.Japanese) japanese_fonts = [font for font in possible_fonts if 'jp' in font.lower()] font = qg.QFont(japanese_fonts[0]) dialog.setFont(font) big_font = qg.QFont(font) big_font.setPointSize(font.pointSize() * 1.5) dialog.pronunciation = qw.QLabel(pronunciation.replace('\t', '')) dialog.pronunciation.setFont(big_font) dialog.pronunciation.setTextInteractionFlags(qc.Qt.TextSelectableByMouse) dialog.writing_button = qw.QPushButton('Check writing') dialog.writing_button.setDefault(True) def check(): dialog.media_player.stop() dialog.accept() callback() dialog.writing_button.clicked.connect(check) vlayout = qw.QVBoxLayout() vlayout.addWidget(dialog.pronunciation) vlayout.addWidget(dialog.writing_button) dialog.setLayout(vlayout) dialog.playlist = qm.QMediaPlaylist() dialog.playlist.addMedia(qc.QUrl.fromLocalFile( os.path.abspath(audio_file))) dialog.playlist.setPlaybackMode(qm.QMediaPlaylist.Loop) dialog.media_player = qm.QMediaPlayer() dialog.media_player.setPlaylist(dialog.playlist) dialog.media_player.play() dialog.show() return dialog