Beispiel #1
0
class VideoMediaView_(MediaView):
    def __init__(self, media, parent):
        super(VideoMediaView_, self).__init__(media, parent)
        self.widget = QVideoWidget(parent)
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)
        self.player.setVideoOutput(self.widget)
        self.widget.setGeometry(media['geometry'])
        self.set_default_widget_prop()
        self.widget.setDisabled(True)

    @Slot()
    def play(self):
        self.finished = 0
        path = '%s/%s' % (self.save_dir, self.options['uri'])
        self.playlist.addMedia(QMediaContent(path))
        self.player.play()

        self.widget.show()
        self.widget.raise_()
        if float(self.duration) > 0:
            self.play_timer.setInterval(int(float(self.duration) * 1000))
            self.play_timer.start()
        self.started_signal.emit()

    @Slot()
    def stop(self, delete_widget=False):
        #---- kong ----
        if not self.widget:
            return False
        self.player.stop()
        self.playlist = None
        self.player = None
        super(VideoMediaView_, self).stop(delete_widget)
        return True
Beispiel #2
0
class MainWindow(QMainWindow):
    def __init__(self):
        global pixmapDict, specialDescriptionDict
        super(MainWindow, self).__init__()
        self.ui = Ui_pipboy()
        self.ui.setupUi(self)

        self.ui.chartContainer.setContentsMargins(0, 0, 0, 0)

        self.anim = QTimeLine(20000, self)
        self.anim.setFrameRange(0, 500)
        self.anim.setLoopCount(0)
        self.anim.setUpdateInterval(16)
        self.anim.frameChanged[int].connect(
            self.ui.perks_description.verticalScrollBar().setValue)
        self.anim.frameChanged[int].connect(
            self.ui.aid_effect_label.verticalScrollBar().setValue)
        self.anim.frameChanged[int].connect(
            self.ui.data_description.verticalScrollBar().setValue)

        #self.anim2 = QPropertyAnimation(self.ui.main_tab, b"pos")
        #self.anim2.setEasingCurve(QEasingCurve.OutBounce)
        #self.anim2.setDuration(2000)
        #self.anim2.setStartValue(QPoint(10, -400))
        #self.anim2.setEndValue(QPoint(10, 0))
        #self.anim2.start()

        self.random = QRandomGenerator.global_()

        self.ui.stat_tab.setFocus()
        self.ui.stat_tab.currentChanged.connect(self.shift)
        self.ui.stat_tab.installEventFilter(self)
        self.ui.inv_tab.installEventFilter(self)

        self.ui.special_list.installEventFilter(self)
        self.ui.perks_list.installEventFilter(self)
        self.ui.test_list.installEventFilter(self)
        self.ui.apparel_list.installEventFilter(self)
        self.ui.aid_list.installEventFilter(self)
        self.ui.ammo_list.installEventFilter(self)
        self.ui.data_list.installEventFilter(self)
        self.ui.radio_list.installEventFilter(self)

        self.ui.main_img.setPixmap(description.main_img_pixmap)

        self.ui.special_image.setPixmap(description.pixmapDict.get(0))
        self.ui.perks_image.setPixmap(description.pixmatPerksDict.get(0))
        self.ui.weapon_image.setPixmap(description.pixmapWeaponDict.get(0))
        self.ui.apparel_image.setPixmap(description.pixmapWeaponDict.get(0))
        self.ui.aid_image.setPixmap(description.pixmapAidDict.get(0))
        self.ui.ammo_image.setPixmap(description.pixmapAmmoDict.get(0))

        lay = QVBoxLayout(self.ui.chartContainer)
        lay.setContentsMargins(0, 0, 0, 0)

        self.chartview = QtCharts.QChartView()
        self.chartview.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(self.chartview)

        self.chart = QtCharts.QChart()
        self.chart.legend().hide()
        self.chart.setAnimationOptions(QtCharts.QChart.SeriesAnimations)

        self.series = QtCharts.QLineSeries()
        self.pen = QPen(QColor(119, 251, 81, 255))
        self.pen.setWidth(3)
        self.pen.setJoinStyle(Qt.RoundJoin)
        self.series.setPen(self.pen)

        backgroundGradient = QLinearGradient(QPointF(100, 100),
                                             QPointF(200, 200))

        backgroundGradient.setColorAt(0, QColor(0, 0, 0, 255))
        backgroundGradient.setColorAt(1, QColor(0, 0, 0, 255))
        self.chart.setBackgroundBrush(backgroundGradient)
        self.chart.setPlotAreaBackgroundBrush(backgroundGradient)

        self.chart.addSeries(self.series)

        self.chart.createDefaultAxes()

        self.chart.axisX(self.series).setVisible(False)
        self.chart.axisY(self.series).setVisible(False)
        self.chart.axisY(self.series).setRange(0, 100)
        self.chartview.setChart(self.chart)

        self.play = False
        self.player = QMediaPlayer()

        self.playlistFalloutNewVegas = QMediaPlaylist(self.player)
        self.playlistFalloutNewVegas.addMedia(
            QMediaContent(description.falooutNewVegas))
        self.playlistFalloutNewVegas.setCurrentIndex(1)

        self.playListMohaveMusic = QMediaPlaylist(self.player)

        for url in description.mohaveMusic:
            self.playListMohaveMusic.addMedia(QMediaContent(url))

        self.playListMohaveMusic.setCurrentIndex(1)

        self.playlisNewVegas = QMediaPlaylist(self.player)

        for url in description.newVegas:
            self.playlisNewVegas.addMedia(QMediaContent(url))

        self.playlisNewVegas.setCurrentIndex(1)

        self.playlistDict = {
            0: self.playlistFalloutNewVegas,
            1: self.playListMohaveMusic,
            2: self.playlisNewVegas
        }

    def append_data_and_plot(self, d):
        """Append and update the plot"""
        num, m = d

        ax1 = self.chart.axisX(self.series)

        xmin = xmax = num

        step = 100

        for p in self.series.pointsVector()[-step:]:
            xmin = min(p.x(), xmin)
            xmax = max(p.x(), xmax)

        xmin = max(0, xmax - step)

        ax1.setMin(xmin)
        ax1.setMax(xmax)

        self.series.append(QPointF(num, m))

    def eventFilter(self, obj, event):
        if event.type() == QEvent.KeyPress:
            #print(obj)
            if event.key() == 49:
                self.ui.main_tab.setCurrentIndex(1)
                self.ui.stat_tab.setFocus()
                #self.ui.hp_head.setValue(self.random.bounded(50, 100))
                #self.ui.hp_left_arm.setValue(self.random.bounded(50, 100))
                #self.ui.hp_right_arm.setValue(self.random.bounded(50, 100))
                #self.ui.hp_left_leg.setValue(self.random.bounded(50, 100))
                #self.ui.hp_right_leg.setValue(self.random.bounded(50, 100))
                #self.ui.hp_body.setValue(self.random.bounded(50, 100))
                return True
            elif event.key() == 50:
                self.ui.main_tab.setCurrentIndex(2)
                self.ui.inv_tab.setFocus()
                return True
            elif event.key() == 51:
                self.ui.main_tab.setCurrentIndex(3)
                self.ui.data_list.setFocus()
                self.ui.data_list.setCurrentRow(0)
                return True
            elif event.key() == 52:
                self.ui.main_tab.setCurrentIndex(4)
                return True
            elif event.key() == 53:
                self.ui.main_tab.setCurrentIndex(5)
                self.ui.radio_list.setFocus()
                self.ui.radio_list.setCurrentRow(0)
                return True
            elif event.key() == 54:
                print(QApplication.focusWidget())
                return True
            #focus from stat_tab to special_list
            elif (obj
                  == self.ui.stat_tab) and (self.ui.stat_tab.currentIndex()
                                            == 1) and (event.key() == 47):
                self.ui.special_list.setFocus()
                self.ui.special_list.setCurrentRow(0)
                self.ui.special_image.setPixmap(description.pixmapDict.get(0))
                self.ui.special_description.setText(
                    description.specialDescriptionDict.get(0))
                return True
            #
            elif (obj == self.ui.special_list) and (event.key() == 16777236):
                self.ui.special_list.setCurrentRow(
                    self.ui.special_list.currentRow() + 1)

                if (self.ui.special_list.currentRow() == -1):
                    self.ui.special_list.setCurrentRow(0)

                self.ui.special_list.scrollToItem(
                    self.ui.special_list.currentItem())

                self.ui.special_image.setPixmap(
                    description.pixmapDict.get(
                        self.ui.special_list.currentRow()))
                self.ui.special_description.setText(
                    description.specialDescriptionDict.get(
                        self.ui.special_list.currentRow()))

            elif (obj == self.ui.special_list) and (event.key() == 16777234):
                self.ui.special_list.setCurrentRow(
                    self.ui.special_list.currentRow() - 1)

                if (self.ui.special_list.currentRow() == -1):
                    self.ui.special_list.setCurrentRow(0)

                self.ui.special_list.scrollToItem(
                    self.ui.special_list.currentItem())

                self.ui.special_image.setPixmap(
                    description.pixmapDict.get(
                        self.ui.special_list.currentRow()))
                self.ui.special_description.setText(
                    description.specialDescriptionDict.get(
                        self.ui.special_list.currentRow()))
            #focus from special_list to stat_tab
            elif (obj == self.ui.special_list) and (event.key() == 47):
                self.ui.special_list.setCurrentRow(-1)
                self.ui.stat_tab.setFocus()
                return True
            # focus from stat_tab to perks_list
            elif (obj
                  == self.ui.stat_tab) and (self.ui.stat_tab.currentIndex()
                                            == 2) and (event.key() == 47):
                self.ui.perks_list.setFocus()
                self.ui.perks_list.setCurrentRow(0)
                self.anim.setCurrentTime(0)
                self.anim.start()
            elif (obj == self.ui.perks_list) and (event.key() == 16777236):
                self.ui.perks_list.setCurrentRow(
                    self.ui.perks_list.currentRow() + 1)

                if (self.ui.perks_list.currentRow() == -1):
                    self.ui.perks_list.setCurrentRow(0)

                self.ui.perks_list.scrollToItem(
                    self.ui.perks_list.currentItem())

                self.ui.perks_image.setPixmap(
                    description.pixmatPerksDict.get(
                        self.ui.perks_list.currentRow()))
                self.ui.perks_description.setText(
                    description.perksDescriptionDict.get(
                        self.ui.perks_list.currentRow()))

                self.anim.stop()
                self.anim.setCurrentTime(0)
                self.anim.start()
            elif (obj == self.ui.perks_list) and (event.key() == 16777234):
                self.ui.perks_list.setCurrentRow(
                    self.ui.perks_list.currentRow() - 1)

                if (self.ui.perks_list.currentRow() == -1):
                    self.ui.perks_list.setCurrentRow(0)

                self.ui.perks_list.scrollToItem(
                    self.ui.perks_list.currentItem())

                self.ui.perks_image.setPixmap(
                    description.pixmatPerksDict.get(
                        self.ui.perks_list.currentRow()))
                self.ui.perks_description.setText(
                    description.perksDescriptionDict.get(
                        self.ui.perks_list.currentRow()))

                self.anim.stop()
                self.anim.setCurrentTime(0)
                self.anim.start()
            #focus from perks_list to stat_tab
            elif (obj == self.ui.perks_list) and (event.key() == 47):
                self.ui.perks_list.setCurrentRow(-1)
                self.ui.stat_tab.setFocus()
                self.anim.stop()
                return True

            #/------------------------------------------------INV-WEAPON--------------------------------------------------/
            elif (obj == self.ui.inv_tab) and (self.ui.inv_tab.currentIndex()
                                               == 0) and (event.key() == 47):
                self.ui.test_list.setFocus()
                self.ui.test_list.setCurrentRow(0)
                return True
            elif (obj == self.ui.test_list) and (event.key() == 47):
                self.ui.test_list.setCurrentRow(-1)
                self.ui.inv_tab.setFocus()
                return True

            elif (obj == self.ui.test_list) and (event.key() == 16777236):
                self.ui.test_list.setCurrentRow(
                    self.ui.test_list.currentRow() + 1)
                if (self.ui.test_list.currentRow() == -1):
                    self.ui.test_list.setCurrentRow(0)
                self.ui.test_list.scrollToItem(self.ui.test_list.currentItem())

                self.ui.weapon_image.setPixmap(
                    description.pixmapWeaponDict.get(
                        self.ui.test_list.currentRow()))

                self.ui.w_damage_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[0])
                self.ui.w_weight_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[1])
                self.ui.w_cost_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[2])
                self.ui.w_durability_PB.setValue(self.random.bounded(20, 100))
                self.ui.w_ammo_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[3])
                self.ui.w_effect_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[4])

            elif (obj == self.ui.test_list) and (event.key() == 16777234):
                self.ui.test_list.setCurrentRow(
                    self.ui.test_list.currentRow() - 1)

                if (self.ui.test_list.currentRow() == -1):
                    self.ui.test_list.setCurrentRow(0)

                self.ui.test_list.scrollToItem(self.ui.test_list.currentItem())

                self.ui.weapon_image.setPixmap(
                    description.pixmapWeaponDict.get(
                        self.ui.test_list.currentRow()))

                self.ui.w_damage_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[0])
                self.ui.w_weight_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[1])
                self.ui.w_cost_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[2])
                self.ui.w_durability_PB.setValue(self.random.bounded(20, 100))
                self.ui.w_ammo_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[3])
                self.ui.w_effect_label.setText(
                    description.weaponDescriptionDict.get(
                        self.ui.test_list.currentRow())[4])

            #/------------------------------------------------INV-APPAREL--------------------------------------------------/
            elif (obj == self.ui.inv_tab) and (self.ui.inv_tab.currentIndex()
                                               == 1) and (event.key() == 47):
                self.ui.apparel_list.setFocus()
                self.ui.apparel_list.setCurrentRow(0)
                return True
            elif (obj == self.ui.apparel_list) and (event.key() == 47):
                self.ui.apparel_list.setCurrentRow(-1)
                self.ui.inv_tab.setFocus()
                return True

            elif (obj == self.ui.apparel_list) and (event.key() == 16777236):
                self.ui.apparel_list.setCurrentRow(
                    self.ui.apparel_list.currentRow() + 1)
                if (self.ui.apparel_list.currentRow() == -1):
                    self.ui.apparel_list.setCurrentRow(0)
                self.ui.apparel_list.scrollToItem(
                    self.ui.apparel_list.currentItem())

                self.ui.apparel_image.setPixmap(
                    description.pixmapClothesDict.get(
                        self.ui.apparel_list.currentRow()))

                self.ui.a_damage_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[0])
                self.ui.a_weight_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[1])
                self.ui.a_cost_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[2])
                self.ui.a_durability_PB.setValue(self.random.bounded(0, 100))
                self.ui.a_type_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[3])
                self.ui.a_effect_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[4])

            elif (obj == self.ui.apparel_list) and (event.key() == 16777234):
                self.ui.apparel_list.setCurrentRow(
                    self.ui.apparel_list.currentRow() - 1)

                if (self.ui.apparel_list.currentRow() == -1):
                    self.ui.apparel_list.setCurrentRow(0)

                self.ui.apparel_list.scrollToItem(
                    self.ui.apparel_list.currentItem())

                self.ui.apparel_image.setPixmap(
                    description.pixmapClothesDict.get(
                        self.ui.apparel_list.currentRow()))

                self.ui.a_damage_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[0])
                self.ui.a_weight_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[1])
                self.ui.a_cost_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[2])
                self.ui.a_durability_PB.setValue(self.random.bounded(0, 100))
                self.ui.a_type_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[3])
                self.ui.a_effect_label.setText(
                    description.clothesDescriptionDict.get(
                        self.ui.apparel_list.currentRow())[4])

            #/------------------------------------------------INV-AID--------------------------------------------------/
            elif (obj == self.ui.inv_tab) and (self.ui.inv_tab.currentIndex()
                                               == 2) and (event.key() == 47):
                self.ui.aid_list.setFocus()
                self.ui.aid_list.setCurrentRow(0)
                return True
            elif (obj == self.ui.aid_list) and (event.key() == 47):
                self.ui.aid_list.setCurrentRow(-1)
                self.ui.inv_tab.setFocus()
                return True

            elif (obj == self.ui.aid_list) and (event.key() == 16777236):
                self.ui.aid_list.setCurrentRow(self.ui.aid_list.currentRow() +
                                               1)
                if (self.ui.aid_list.currentRow() == -1):
                    self.ui.aid_list.setCurrentRow(0)
                self.ui.aid_list.scrollToItem(self.ui.aid_list.currentItem())

                self.ui.aid_image.setPixmap(
                    description.pixmapAidDict.get(
                        self.ui.aid_list.currentRow()))

                self.ui.aid_weight_label.setText(
                    description.aidDescriptionDict.get(
                        self.ui.aid_list.currentRow())[0])
                self.ui.aid_cost_label.setText(
                    description.aidDescriptionDict.get(
                        self.ui.aid_list.currentRow())[1])
                self.ui.aid_effect_label.setText(
                    description.aidDescriptionDict.get(
                        self.ui.aid_list.currentRow())[2])

                self.anim.stop()
                self.anim.setCurrentTime(0)
                self.anim.start()
            elif (obj == self.ui.aid_list) and (event.key() == 16777234):
                self.ui.aid_list.setCurrentRow(self.ui.aid_list.currentRow() -
                                               1)

                if (self.ui.aid_list.currentRow() == -1):
                    self.ui.aid_list.setCurrentRow(0)

                self.ui.aid_list.scrollToItem(self.ui.aid_list.currentItem())

                self.ui.aid_image.setPixmap(
                    description.pixmapAidDict.get(
                        self.ui.aid_list.currentRow()))

                self.ui.aid_weight_label.setText(
                    description.aidDescriptionDict.get(
                        self.ui.aid_list.currentRow())[0])
                self.ui.aid_cost_label.setText(
                    description.aidDescriptionDict.get(
                        self.ui.aid_list.currentRow())[1])
                self.ui.aid_effect_label.setText(
                    description.aidDescriptionDict.get(
                        self.ui.aid_list.currentRow())[2])

                self.anim.stop()
                self.anim.setCurrentTime(0)
                self.anim.start()
            #/------------------------------------------------INV-AMMO--------------------------------------------------/
            elif (obj == self.ui.inv_tab) and (self.ui.inv_tab.currentIndex()
                                               == 3) and (event.key() == 47):
                self.ui.ammo_list.setFocus()
                self.ui.ammo_list.setCurrentRow(0)
                return True
            elif (obj == self.ui.ammo_list) and (event.key() == 47):
                self.ui.ammo_list.setCurrentRow(-1)
                self.ui.inv_tab.setFocus()
                return True

            elif (obj == self.ui.ammo_list) and (event.key() == 16777236):
                self.ui.ammo_list.setCurrentRow(
                    self.ui.ammo_list.currentRow() + 1)
                if (self.ui.ammo_list.currentRow() == -1):
                    self.ui.ammo_list.setCurrentRow(0)
                self.ui.ammo_list.scrollToItem(self.ui.ammo_list.currentItem())

                self.ui.ammo_image.setPixmap(
                    description.pixmapAmmoDict.get(
                        self.ui.ammo_list.currentRow()))

                self.ui.ammo_weight_label.setText(
                    description.ammoDescriptionDict.get(
                        self.ui.ammo_list.currentRow())[0])
                self.ui.ammo_cost_label.setText(
                    description.ammoDescriptionDict.get(
                        self.ui.ammo_list.currentRow())[1])

            elif (obj == self.ui.ammo_list) and (event.key() == 16777234):
                self.ui.ammo_list.setCurrentRow(
                    self.ui.ammo_list.currentRow() - 1)

                if (self.ui.ammo_list.currentRow() == -1):
                    self.ui.ammo_list.setCurrentRow(0)

                self.ui.ammo_list.scrollToItem(self.ui.ammo_list.currentItem())

                self.ui.ammo_image.setPixmap(
                    description.pixmapAmmoDict.get(
                        self.ui.ammo_list.currentRow()))

                self.ui.ammo_weight_label.setText(
                    description.ammoDescriptionDict.get(
                        self.ui.ammo_list.currentRow())[0])
                self.ui.ammo_cost_label.setText(
                    description.ammoDescriptionDict.get(
                        self.ui.ammo_list.currentRow())[1])

            #/------------------------------------------------DATA--------------------------------------------------/
            elif (obj == self.ui.data_list) and (event.key() == 16777236):
                self.ui.data_list.setCurrentRow(
                    self.ui.data_list.currentRow() + 1)

                if (self.ui.data_list.currentRow() == -1):
                    self.ui.data_list.setCurrentRow(0)

                self.ui.data_list.scrollToItem(self.ui.data_list.currentItem())

                self.ui.data_description.setText(
                    description.questDescriptionDict.get(
                        self.ui.data_list.currentRow()))

                self.anim.stop()
                self.anim.setCurrentTime(0)
                self.anim.start()
            elif (obj == self.ui.data_list) and (event.key() == 16777234):
                self.ui.data_list.setCurrentRow(
                    self.ui.data_list.currentRow() - 1)

                if (self.ui.data_list.currentRow() == -1):
                    self.ui.data_list.setCurrentRow(0)

                self.ui.data_list.scrollToItem(self.ui.data_list.currentItem())

                self.ui.data_description.setText(
                    description.questDescriptionDict.get(
                        self.ui.data_list.currentRow()))

                self.anim.stop()
                self.anim.setCurrentTime(0)
                self.anim.start()

            #/------------------------------------------------RADIO--------------------------------------------------/
            elif (obj == self.ui.radio_list) and (event.key() == 16777236):
                self.ui.radio_list.setCurrentRow(
                    self.ui.radio_list.currentRow() + 1)

                if (self.ui.radio_list.currentRow() == -1):
                    self.ui.radio_list.setCurrentRow(0)

            elif (obj == self.ui.radio_list) and (event.key() == 16777234):
                self.ui.radio_list.setCurrentRow(
                    self.ui.radio_list.currentRow() - 1)

                if (self.ui.radio_list.currentRow() == -1):
                    self.ui.radio_list.setCurrentRow(0)

                #self.ui.data_description.setText(description.questDescriptionDict.get(self.ui.radio_list.currentRow()))
            elif (obj == self.ui.radio_list) and (event.key() == 47):
                if self.play:
                    self.player.stop()
                    self.play = False
                else:
                    self.player.setPlaylist(
                        self.playlistDict.get(self.ui.radio_list.currentRow()))
                    self.playListMohaveMusic.setCurrentIndex(
                        self.random.bounded(0, 9) + 1)
                    self.playlisNewVegas.setCurrentIndex(
                        self.random.bounded(0, 10) + 1)

                    self.player.play()
                    self.play = True
                return True
            else:
                #print(event.key())
                return True

        return super(MainWindow, self).eventFilter(obj, event)

    @Slot()
    def shift(self):
        print(self.ui.stat_tab.currentIndex())

        index = self.ui.stat_tab.currentIndex()
        if index == 0:
            self.ui.stat_tab.setGeometry(0, 0, 904, 380)
        elif index == 1:
            self.ui.stat_tab.setGeometry(-108, 0, 904, 380)
        elif index == 2:
            self.ui.stat_tab.setGeometry(-214, 0, 904, 380)
Beispiel #3
0
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()
Beispiel #4
0
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
Beispiel #5
0
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('开始捕获')
Beispiel #6
0
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())
Beispiel #7
0
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))
Beispiel #8
0
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()
Beispiel #9
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(
            self
        )  #permet de charger tous les composants graphiques coder dans un autre fichier
        # partir du fichier .py (au lieu du .ui) permet d'accéder à la complétion cad la liste des fonctions, widgets...

        self.ui.pbLect.clicked.connect(self.lectClicked)
        self.ui.pbPause.clicked.connect(self.pauseClicked)
        self.ui.pbStop.clicked.connect(self.stopClicked)
        self.ui.pbPreced.clicked.connect(self.precedClicked)
        self.ui.pbSuiv.clicked.connect(self.suivClicked)
        # self.ui.pbAjout.clicked.connect(self.ajoutClicked)
        self.ui.pbAjout.clicked.connect(self.ajoutClicked2)
        self.ui.pbSuppr.clicked.connect(self.supprClicked)
        self.ui.dlVolume.valueChanged.connect(self.volumeChange)

        self.mediaPlayer = QMediaPlayer()
        self.mediaPlayer.setVideoOutput(self.ui.videoScreen)

        self.mediaPlayer.durationChanged.connect(self.mediaDurationChanged)
        self.mediaPlayer.positionChanged.connect(self.mediaPositionChanged)
        self.ui.slTimeBarre.valueChanged.connect(self.timeBarreChanged)

        self.ui.listFilm.itemDoubleClicked.connect(
            self.filmSelectDC)  #film démmarre si double clique sur son titre
        # self.ui.listFilm.itemClicked.connect(self.filmSelectSC)

    def filmSelectDC(self):  #double clique
        currentItem = self.ui.listFilm.currentItem()
        mediaContent = QMediaContent(QUrl.fromLocalFile(
            currentItem.toolTip()))  #currentItem.text() si ajoutClicked
        self.mediaPlayer.setMedia(mediaContent)
        self.lectClicked()

    # def filmSelectSC(self): #simple clique
    #     currentItem = self.ui.listFilm.currentItem()
    #     mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.toolTip()))  #currentItem.text() si ajoutClicked
    #     self.mediaPlayer.setMedia(mediaContent)

    # def mediaSelected2(self):
    #     currentItem = self.ui.listFilm.currentItem()
    #     mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.toolTip()))  #currentItem.text() si ajoutClicked
    #     self.mediaPlayer.setMedia(mediaContent)
    #     self.lectureClicked()

    def lectClicked(self):
        print("Lecture!!")
        self.mediaPlayer.play()

    def pauseClicked(self):
        #print("Pause")
        self.mediaPlayer.pause()

    def stopClicked(self):
        #print("Stop")
        self.mediaPlayer.stop()

    # def ajoutClicked(self):
    #     print("Ajout")
    #     ajoutFilm = QFileDialog.getOpenFileName(self, "Choix Film", "C:/Users/AELION/BCH/Qt_interface_graphique/QtPython_ExoLecteurVideo", "Movie Files(*.avi *.mp4)")
    #     item = QListWidgetItem(ajoutFilm[0])
    #     self.ui.listFilm.addItem(item)

    def ajoutClicked2(self):
        # print("Ajout2")
        nomMedia = QFileDialog.getOpenFileName(
            self, "Choix Film",
            "C:/Users/AELION/BCH/Qt_interface_graphique/QtPython_ExoLecteurVideo",
            "Movie Files(*.avi *.mp4)")
        if nomMedia[
                0] == "":  # si aucun fichier selectionné pour éviter l'affichage d'une ligne vide dans la liste
            return
        fInfo = QFileInfo(nomMedia[0])
        fShortName = fInfo.baseName()
        item = QListWidgetItem(fShortName)
        item.setToolTip(
            nomMedia[0]
        )  #permet en plus d'afficher bandeau info fichier quand survol souris
        self.ui.listFilm.addItem(item)

    def supprClicked(self):
        # print("Supprime")
        supprFilm = self.ui.listFilm.currentRow()
        if supprFilm != -1:  #-1 retourner quand rien à supprimer, sinon bug
            self.ui.listFilm.takeItem(supprFilm)

    def volumeChange(self):
        #print("Volume %s" %self.ui.dlVolume.value())
        self.mediaPlayer.setVolume(self.ui.dlVolume.value())
        self.ui.lbVolumePourc.setText(str(self.ui.dlVolume.value()) + "%")

    def mediaDurationChanged(self):
        mediaDuration = self.mediaPlayer.duration()
        self.ui.slTimeBarre.setRange(0, mediaDuration)
        totTime = QTime(0, 0, 0)
        totTime = totTime.addMSecs(mediaDuration)
        self.ui.lbTimeTot.setText(totTime.toString("HH:mm:ss"))

    def mediaPositionChanged(self):
        self.ui.slTimeBarre.valueChanged.disconnect(self.timeBarreChanged)
        mediaPosition = self.mediaPlayer.position()
        self.ui.slTimeBarre.setValue(mediaPosition)
        currentTime = QTime(0, 0, 0)
        currentTime = currentTime.addMSecs(mediaPosition)
        self.ui.lbTimeReal.setText(currentTime.toString("HH:mm:ss"))
        self.ui.slTimeBarre.valueChanged.connect(self.timeBarreChanged)

    def timeBarreChanged(self):
        self.mediaPlayer.positionChanged.disconnect(self.mediaPositionChanged)
        self.mediaPlayer.setPosition(self.ui.slTimeBarre.value())
        self.mediaPlayer.positionChanged.connect(self.mediaPositionChanged)

    def precedClicked(self):
        print("Précédent")

    def suivClicked(self):
        print("Suivant")
Beispiel #10
0
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
Beispiel #11
0
class Form(QMainWindow):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setObjectName("MainWindow")
        self.resize(804, 559)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,
                                           QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        self.centralwidget = QtWidgets.QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.wVideo = QVideoWidget(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.wVideo.sizePolicy().hasHeightForWidth())
        self.wVideo.setSizePolicy(sizePolicy)
        self.wVideo.setObjectName("wVideo")
        self.verticalLayout.addWidget(self.wVideo)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.lStartTime = QtWidgets.QLabel(self.centralwidget)
        self.lStartTime.setObjectName("lStartTime")
        self.horizontalLayout_2.addWidget(self.lStartTime)
        self.sProgression = QtWidgets.QSlider(self.centralwidget)
        self.sProgression.setOrientation(QtCore.Qt.Horizontal)
        self.sProgression.setObjectName("sProgression")
        self.horizontalLayout_2.addWidget(self.sProgression)
        self.lEndTime = QtWidgets.QLabel(self.centralwidget)
        self.lEndTime.setObjectName("lEndTime")
        self.horizontalLayout_2.addWidget(self.lEndTime)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.lBoutons = QtWidgets.QHBoxLayout()
        self.lBoutons.setObjectName("lBoutons")
        self.pbLecture = QtWidgets.QPushButton(self.centralwidget)
        self.pbLecture.setObjectName("pbLecture")
        self.lBoutons.addWidget(self.pbLecture)
        self.pbPause = QtWidgets.QPushButton(self.centralwidget)
        self.pbPause.setObjectName("pbPause")
        self.lBoutons.addWidget(self.pbPause)
        self.pbStop = QtWidgets.QPushButton(self.centralwidget)
        self.pbStop.setObjectName("pbStop")
        self.lBoutons.addWidget(self.pbStop)
        self.pbSuivant = QtWidgets.QPushButton(self.centralwidget)
        self.pbSuivant.setObjectName("pbSuivant")
        self.lBoutons.addWidget(self.pbSuivant)
        self.pbPrecedent = QtWidgets.QPushButton(self.centralwidget)
        self.pbPrecedent.setObjectName("pbPrecedent")
        self.lBoutons.addWidget(self.pbPrecedent)
        self.verticalLayout.addLayout(self.lBoutons)
        self.horizontalLayout.addLayout(self.verticalLayout)
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setBaseSize(QtCore.QSize(0, 0))
        self.line.setFrameShape(QtWidgets.QFrame.VLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.verticalLayout_3.addWidget(self.line)
        spacerItem = QtWidgets.QSpacerItem(20, 100,
                                           QtWidgets.QSizePolicy.Minimum,
                                           QtWidgets.QSizePolicy.Fixed)
        self.verticalLayout_3.addItem(spacerItem)
        self.horizontalLayout.addLayout(self.verticalLayout_3)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setObjectName("label_3")
        self.verticalLayout_2.addWidget(self.label_3)
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum,
                                           QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.listWidget.sizePolicy().hasHeightForWidth())
        self.listWidget.setSizePolicy(sizePolicy)
        self.listWidget.setObjectName("listWidget")
        self.verticalLayout_2.addWidget(self.listWidget)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        spacerItem1 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem1)
        self.pbAjout = QtWidgets.QPushButton(self.centralwidget)
        self.pbAjout.setObjectName("pbAjout")
        self.horizontalLayout_3.addWidget(self.pbAjout)
        self.pbSuppr = QtWidgets.QPushButton(self.centralwidget)
        self.pbSuppr.setObjectName("pbSuppr")
        self.horizontalLayout_3.addWidget(self.pbSuppr)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        spacerItem2 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_4.addItem(spacerItem2)
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_4.addWidget(self.label_4)
        self.dVolume = QtWidgets.QDial(self.centralwidget)
        self.dVolume.setObjectName("dVolume")
        self.horizontalLayout_4.addWidget(self.dVolume)
        self.lPourcentVolume = QtWidgets.QLabel(self.centralwidget)
        self.lPourcentVolume.setObjectName("lPourcentVolume")
        self.horizontalLayout_4.addWidget(self.lPourcentVolume)
        self.verticalLayout_2.addLayout(self.horizontalLayout_4)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.horizontalLayout_5.addLayout(self.horizontalLayout)
        self.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(self)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 804, 21))
        self.menubar.setObjectName("menubar")
        self.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.retranslateUi(self)
        QtCore.QMetaObject.connectSlotsByName(self)

        self.mediaPlayer = QMediaPlayer()
        self.mediaPlayer.setVideoOutput(self.wVideo)

        self.pbLecture.clicked.connect(self.lectureClic)
        self.pbPause.clicked.connect(self.pauseClic)
        self.pbStop.clicked.connect(self.stopClic)
        self.pbSuivant.clicked.connect(self.suivantClic)
        self.pbPrecedent.clicked.connect(self.precedentClic)
        self.dVolume.valueChanged.connect(self.volumeChange)
        self.mediaPlayer.positionChanged.connect(self.progressionChange)
        self.sProgression.sliderMoved.connect(self.progressionDeplace)
        self.pbSuppr.clicked.connect(self.supprVid)
        self.pbAjout.clicked.connect(self.addVid)
        self.listWidget.itemDoubleClicked.connect(self.listeDoubleClic)

        self.dVolume.setMaximum(100)
        self.lEndTime.setText("")
        self.lStartTime.setText("")
        self.lPourcentVolume.setText("")
        self.dVolume.setValue(31)

    def progressionDeplace(self):
        self.mediaPlayer.setPosition(self.sProgression.value())

    def progressionChange(self):
        self.lEndTime.setText(convertMillis(self.mediaPlayer.duration()))
        self.lStartTime.setText(str(convertMillis(
            self.mediaPlayer.position())))
        self.sProgression.setRange(0, self.mediaPlayer.duration())
        self.sProgression.setValue(self.mediaPlayer.position())

    def lectureClic(self):
        mediaContent = QMediaContent(QUrl.fromLocalFile(self.openFile[0]))
        self.mediaPlayer.setMedia(mediaContent)
        self.mediaPlayer.play()

    def pauseClic(self):
        print("Pause")
        if self.mediaPlayer.state() == QMediaPlayer.PausedState:
            self.mediaPlayer.play()
        else:
            self.mediaPlayer.pause()

    def stopClic(self):
        self.mediaPlayer.stop()

    def suivantClic(self):
        currentItemRow = self.listWidget.currentRow()
        if currentItemRow == -1:
            return
        totalItems = self.listWidget.count()
        self.listWidget.setCurrentRow((currentItemRow + 1) % totalItems)
        self.listeDoubleClic()

    def precedentClic(self):
        currentItemRow = self.listWidget.currentRow()
        if currentItemRow == -1:
            return
        totalItems = self.listWidget.count()
        self.listWidget.setCurrentRow((currentItemRow - 1) % totalItems)
        self.listeDoubleClic()

    def volumeChange(self):
        self.lPourcentVolume.setText(str(self.dVolume.value()))
        self.mediaPlayer.setVolume(self.dVolume.value())

    def supprVid(self):
        if self.listWidget.currentRow() != -1:
            self.listWidget.takeItem(self.listWidget.currentRow())

    def addVid(self):
        self.openFile = QFileDialog.getOpenFileName(
            self, "Ouvrir...", ".", "Image Files (*.avi *.mp4)")
        self.listWidget.addItem(self.openFile[0])

    def listeDoubleClic(self):
        self.mediaPlayer.setMedia(
            QMediaContent(
                QUrl.fromLocalFile(self.listWidget.currentItem().text())))
        self.mediaPlayer.play()

    def retranslateUi(self, MainWindow):
        self.setWindowTitle(
            QtWidgets.QApplication.translate("MainWindow", "MainWindow", None,
                                             -1))
        self.lStartTime.setText(
            QtWidgets.QApplication.translate("MainWindow", "$start_time", None,
                                             -1))
        self.lEndTime.setText(
            QtWidgets.QApplication.translate("MainWindow", "$end_time", None,
                                             -1))
        self.pbLecture.setText(
            QtWidgets.QApplication.translate("MainWindow", "Lecture", None,
                                             -1))
        self.pbPause.setText(
            QtWidgets.QApplication.translate("MainWindow", "Pause", None, -1))
        self.pbStop.setText(
            QtWidgets.QApplication.translate("MainWindow", "Stop", None, -1))
        self.pbSuivant.setText(
            QtWidgets.QApplication.translate("MainWindow", "Suivant", None,
                                             -1))
        self.pbPrecedent.setText(
            QtWidgets.QApplication.translate("MainWindow", "Précédent", None,
                                             -1))
        self.label_3.setText(
            QtWidgets.QApplication.translate("MainWindow",
                                             "Liste de lecture :", None, -1))
        self.pbAjout.setText(
            QtWidgets.QApplication.translate("MainWindow", "+", None, -1))
        self.pbSuppr.setText(
            QtWidgets.QApplication.translate("MainWindow", "-", None, -1))
        self.label_4.setText(
            QtWidgets.QApplication.translate("MainWindow", "Volume :", None,
                                             -1))
        self.lPourcentVolume.setText(
            QtWidgets.QApplication.translate("MainWindow", "$volume", None,
                                             -1))
Beispiel #12
0
class YoutubePlayer(QObject):

    titlesListChanged = Signal(list)

    def __init__(self,
                 titles: List[Title] = [],
                 widgetToPlay: QVideoWidget = None):
        QObject.__init__(self)

        self.__titles = titles
        self.__playlist = QMediaPlaylist(self)
        self.__player = QMediaPlayer(self)
        self.__videoWidget = widgetToPlay
        self.__player.setVideoOutput(self.__videoWidget)

        self.titlesListChanged.connect(self.resetPlayList)

    @property
    def titles(self):
        return self.__titles

    @titles.setter
    def titles(self, value):
        self.__titles = value
        self.titlesListChanged.emit(self.__titles)

    @Slot()
    def setTitles(self, titles: List[Title]):

        self.__titles = titles
        self.titlesListChanged.emit(self.__titles)

    @Slot()
    def resetPlayList(self, list_of_titles: List[Title]):
        self.__playlist.clear()

        for t in list_of_titles:
            url = t.link
            video = pafy.new(url)
            best = video.getbest()

            self.__playlist.addMedia(QMediaContent(QUrl(best.url)))

        self.__playlist.setCurrentIndex(0)
        self.__player.setPlaylist(self.__playlist)

    @Slot()
    def playVideo(self, index: int):

        self.__playlist.setCurrentIndex(index)
        self.__player.play()

    @Slot()
    def stopVideo(self):

        self.__player.stop()

    @Slot()
    def pauseVideo(self):
        if self.__player.state() == QMediaPlayer.PlayingState:
            self.__player.pause()
        else:
            self.__player.play()
Beispiel #13
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #Connection du decodeur et lecteur
        self.mediaPlayer = QMediaPlayer()
        self.mediaPlayer.setVideoOutput(self.ui.ecranWidget)

        #chargement du media
        mediaContent = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi"))
        self.mediaPlayer.setMedia(mediaContent)

       #connect push boutons
        self.ui.pbLecture.clicked.connect(self.lectureClicked)
        self.ui.pbPause.clicked.connect(self.pauseClicked)
        self.ui.pbStop.clicked.connect(self.stopClicked)
        self.ui.dialVolume.valueChanged.connect(self.volControl)
        self.ui.nivoVolume.setText(str(self.ui.dialVolume.value()))
        self.ui.nivoVolume.setText('{}%'.format(str(self.ui.dialVolume.value())))
        self.mediaPlayer.durationChanged.connect(self.affTemp)
        self.mediaPlayer.positionChanged.connect(self.avanceTemp)
        self.ui.barreLect.valueChanged.connect(self.avanceSlider)
        self.ui.pbPlus.clicked.connect(self.pbPlusCtrl)
        self.ui.pbMoins.clicked.connect(self.pbMoinsCtrl)
        self.ui.listWidget.itemDoubleClicked.connect(self.mediaSelected)
        self.ui.pbSuivant.clicked.connect(self.suivantBouton)
        self.ui.pbPrecedent.clicked.connect(self.precedentBouton)



    #fonction qui gere les click
    def lectureClicked(self):
        self.mediaPlayer.play()

    def pauseClicked(self):

      if  self.mediaPlayer.state() == QMediaPlayer.PausedState :
          self.mediaPlayer.play()
      else :
        self.mediaPlayer.pause()

    def stopClicked(self):
        self.mediaPlayer.stop()

    def volControl(self):
        self.mediaPlayer.setVolume(self.ui.dialVolume.value())
        self.ui.nivoVolume.setText('{}%'.format(str(self.ui.dialVolume.value())))

    def affTemp(self):
        tempTotl = QTime(0, 0, 0)
        tempTotl = tempTotl.addMSecs(self.mediaPlayer.duration() - self.mediaPlayer.position())

        posTemp = QTime(0, 0, 0)
        posTemp = posTemp.addMSecs((self.mediaPlayer.position()))

        self.ui.tempRestant.setText("- {}".format(tempTotl.toString("HH:mm:ss")))
        self.ui.tempLecture.setText(posTemp.toString("HH:mm:ss"))
        self.ui.barreLect.setRange(0,self.mediaPlayer.duration())

    def avanceTemp(self):
        tempTotl= QTime(0,0,0)
        tempTotl = tempTotl.addMSecs(self.mediaPlayer.duration()-self.mediaPlayer.position())


        posTemp= QTime(0,0,0)
        posTemp = posTemp.addMSecs((self.mediaPlayer.position()))

        self.ui.tempRestant.setText("-{}".format(tempTotl.toString("HH:mm:ss")))
        self.ui.tempLecture.setText(posTemp.toString("HH:mm:ss"))
        self.ui.barreLect.setSliderPosition(self.mediaPlayer.position())

    def avanceSlider(self):
        self.mediaPlayer.setPosition(self.ui.barreLect.sliderPosition())

    def pbPlusCtrl(self):

        fileName = QFileDialog.getOpenFileName(self,"choix film","/home","Film(*.avi *.mp4)")
        fInfo = QFileInfo(fileName[0])
        fShortName = fInfo.baseName()
        item = QListWidgetItem(fShortName)
        item.setToolTip(fileName[0])
        self.ui.listWidget.addItem(item)
        print(item.toolTip().title())

    def pbMoinsCtrl(self):
        rowItem= self.ui.listWidget.currentRow()
        if rowItem != -1:
            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 suivantBouton(self):

        if self.ui.listWidget.count() != 0 :
            self.ui.listWidget.setCurrentRow((self.ui.listWidget.currentRow()+1) % self.ui.listWidget.count() )
            mediaContent = QMediaContent(QUrl.fromLocalFile(self.ui.listWidget.currentItem().toolTip()))
            self.mediaPlayer.setMedia(mediaContent)
            self.lectureClicked()

    def precedentBouton(self):

        if self.ui.listWidget.count() != 0 :
            self.ui.listWidget.setCurrentRow((self.ui.listWidget.currentRow()-1) % self.ui.listWidget.count() )
            mediaContent = QMediaContent(QUrl.fromLocalFile(self.ui.listWidget.currentItem().toolTip()))
            self.mediaPlayer.setMedia(mediaContent)
            self.lectureClicked()
Beispiel #14
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setFixedWidth(540)
        self.sound = QMediaPlayer()
        self.executeToken = False
        self.setAcceptDrops(True)
        self.installEventFilter(self)
        self.presetIndex = '0'
        if os.path.exists('utils/config.json'):
            with codecs.open('utils/config.json', 'r', 'utf_8_sig') as config:
                config = config.read()
            self.config = json.loads(config)
        else:
            self.config = {
                str(x): {
                    'gift': '请输入礼物名字 多个礼物间用空格隔开',
                    'words': '感谢 {用户} 投喂的{数量}个{礼物}~',
                    'bgm_path': '',
                    'volume': 100,
                    'gif_path': '',
                    'gif_scale': 50,
                    'second': 4,
                    'font_color': '#3c9dca',
                    'out_color': '#1c54a7',
                    'out_size': 15,
                    'font_name': '微软雅黑',
                    'font_size': 36,
                    'font_bold': False,
                    'font_italic': False
                }
                for x in range(10)
            }
            self.config['0']['gift'] = (
                '辣条 小心心 “棋”开得胜 盛典门票 盛典之杯 吃瓜 冰阔落 给大佬递茶 打榜 盛典小电视 '
                'B坷垃 天空之翼 摩天大楼 礼花 凉了 比心 喵娘 节奏风暴 疯狂打call 泡泡机 爱之魔力 '
                '摩天轮 转运锦鲤 冲浪 亿圆')
            self.config['9']['words'] = '恭迎 {用户} 上舰~~~'
            self.config['room_url'] = '123456'
            self.config['background_color'] = '#00d600'
            self.config['opacity'] = False
            self.config['top'] = False
        self.gift = self.config['0']['gift']
        self.second = self.config['0']['second']
        self.color = self.config['0']['font_color']
        self.outColor = self.config['0']['out_color']
        self.outSize = self.config['0']['out_size']
        self.gifScale = self.config['0']['gif_scale']
        self.gifSize = None
        self.volume = self.config['0']['volume']
        self.oldBGM = self.config['0']['bgm_path']
        self.movieList = []
        self.gifSizeList = []
        for index in [str(i) for i in range(10)]:
            movie = QMovie(self.config[index]['gif_path'])
            gifSize = QPixmap(self.config[index]['gif_path']).size()
            if gifSize:
                movie.setScaledSize(gifSize * self.config[index]['gif_scale'] /
                                    50)
            self.movieList.append(movie)
            self.gifSizeList.append(gifSize)
        self.option = OptionWidget(self.config['background_color'],
                                   self.config['opacity'], self.config['top'])
        self.option.color.connect(self.selectBackgroundColor)
        self.option.opacity.connect(self.setopacity)
        self.option.top.connect(self.setTop)

        self.GIFWidget = GIFWidget(self.movieList[0], self.config['opacity'],
                                   self.config['top'], self.second * 60,
                                   self.color, self.outColor)
        self.GIFWidget.showText.w = self.outSize / 250
        self.GIFWidget.setBackgroundColor(self.config['background_color'])
        self.GIFWidget.finish.connect(self.animateFinish)
        self.GIFWidget.moveDelta.connect(self.changeCenter)
        self.GIFWidget.setText(self.config['0']['words'], 'gift')
        w, h = self.GIFWidget.width(), self.GIFWidget.height()
        x, y = self.GIFWidget.pos().x(), self.GIFWidget.pos().y()
        self.GIFWidgetCenterPos = QPoint(x + w / 2, y + h / 2)

        self.setWindowTitle('DD答谢机 V1.0  (by 执明神君)')
        self.main_widget = QWidget()
        self.main_widget.setAcceptDrops(True)
        self.setCentralWidget(self.main_widget)
        layout = QGridLayout()
        self.main_widget.setLayout(layout)
        self.roomIDLabel = QLabel('B站直播房间')
        self.roomIDLabel.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.roomIDLabel, 0, 0, 1, 1)
        self.biliLiveLabel = QLabel('https://live.bilibili.com/')
        layout.addWidget(self.biliLiveLabel, 0, 2, 1, 2)
        self.roomURLEdit = QLineEdit(self.config['room_url'])
        self.roomURLEdit.setValidator(QIntValidator(0, 2000000000))
        self.roomURLEdit.textChanged.connect(self.setURL)
        layout.addWidget(self.roomURLEdit, 0, 4, 1, 3)

        self.presetCombobox = QComboBox()
        self.presetCombobox.addItems(['    礼物预设%d' % x
                                      for x in range(1, 10)] + ['    舰长上船'])
        self.presetCombobox.currentIndexChanged.connect(self.changePreset)
        layout.addWidget(self.presetCombobox, 1, 0, 1, 1)
        self.giftEdit = QLineEdit(self.gift)
        self.giftEdit.textChanged.connect(self.changeGift)
        layout.addWidget(self.giftEdit, 1, 2, 1, 5)

        self.defaultWordsButton = QPushButton('重置台词')
        self.defaultWordsButton.clicked.connect(self.setDefaultWords)
        layout.addWidget(self.defaultWordsButton, 2, 0, 1, 1)
        self.wordsEdit = QLineEdit(self.config['0']['words'])
        self.wordsEdit.textChanged.connect(self.setWords)
        layout.addWidget(self.wordsEdit, 2, 2, 1, 5)

        self.fontButton = QPushButton('字体设置')
        self.fontButton.clicked.connect(self.getFont)
        layout.addWidget(self.fontButton, 3, 0, 1, 1)
        self.fontLabel = QLabel()
        fontInfo = '%s  %s  %s  ' % (self.config['0']['font_name'],
                                     self.config['0']['font_size'],
                                     self.config['0']['font_color'])
        self.font = QFont(self.config['0']['font_name'],
                          self.config['0']['font_size'])
        if self.config['0']['font_bold']:
            self.font.setBold(self.config['0']['font_bold'])
            fontInfo += '加粗  '
        if self.config['0']['font_italic']:
            self.font.setItalic(self.config['0']['font_italic'])
            fontInfo += '斜体'
        self.fontLabel.setText(fontInfo)
        self.fontLabel.setStyleSheet('color:' + self.color)
        self.GIFWidget.setFont(self.font)
        self.GIFWidget.setColor(self.color)
        layout.addWidget(self.fontLabel, 3, 2, 1, 5)

        self.outLineButton = QPushButton('描边颜色')
        self.outLineButton.clicked.connect(self.setOutLine)
        layout.addWidget(self.outLineButton, 4, 0, 1, 1)
        self.outLineLabel = QLabel(self.outColor)
        self.outLineLabel.setStyleSheet('color:' + self.outColor)
        layout.addWidget(self.outLineLabel, 4, 2, 1, 1)
        self.outLineSizeLabel = QLabel('粗细')
        self.outLineSizeLabel.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.outLineSizeLabel, 4, 4, 1, 1)
        self.outLineSizeBar = Slider()
        self.outLineSizeBar.setMaximum(100)
        self.outLineSizeBar.setValue(self.outSize)
        self.outLineSizeBar.pointClicked.connect(self.sizeChange)
        layout.addWidget(self.outLineSizeBar, 4, 5, 1, 2)

        self.bgmButton = QPushButton('音效设置')
        self.bgmButton.clicked.connect(self.selectBGM)
        layout.addWidget(self.bgmButton, 5, 0, 1, 1)
        self.bgmEdit = QLabel(os.path.split(self.config['0']['bgm_path'])[1])
        self.sound.setMedia(QUrl.fromLocalFile(self.config['0']['bgm_path']))
        layout.addWidget(self.bgmEdit, 5, 2, 1, 2)
        self.volumeLabel = QLabel('音量')
        self.volumeLabel.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.volumeLabel, 5, 4, 1, 1)
        self.volumeBar = Slider()
        self.volumeBar.setMaximum(100)
        self.volumeBar.setValue(self.volume)
        self.volumeBar.pointClicked.connect(self.changevolume)
        layout.addWidget(self.volumeBar, 5, 5, 1, 2)

        self.animeSecond = QLabel('持续时间')
        self.animeSecond.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.animeSecond, 6, 0, 1, 1)
        self.animeSecondComboBox = QComboBox()
        self.animeSecondComboBox.addItems([str(i) + '秒' for i in range(1, 31)])
        self.animeSecondComboBox.setCurrentIndex(self.second - 1)
        self.animeSecondComboBox.currentIndexChanged.connect(self.setSecond)
        layout.addWidget(self.animeSecondComboBox, 6, 2, 1, 2)

        self.scaledValue = QLabel('大小')
        self.scaledValue.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.scaledValue, 6, 4, 1, 1)
        self.scaledBar = Slider()
        self.scaledBar.setValue(self.gifScale)
        self.scaledBar.pointClicked.connect(self.scaleChange)
        layout.addWidget(self.scaledBar, 6, 5, 1, 2)

        self.advancedButton = QPushButton('高级设置')
        self.advancedButton.clicked.connect(self.popOption)
        layout.addWidget(self.advancedButton, 7, 0, 1, 1)

        self.preview = previewLabel('点击或拖入要播放的答谢gif动图')
        self.preview.setFrameShape(QFrame.Box)
        self.preview.setStyleSheet('border:2px dotted #cfcfd0')
        self.preview.setMaximumSize(522, 400)
        self.preview.click.connect(self.click)
        if self.config['0']['gif_path']:
            self.gifSize = self.gifSizeList[0]
            self.movie = self.movieList[0]
            self.movie.setScaledSize(self.gifSize * self.gifScale / 50)
            self.preview.setMovie(self.movie)
            # self.GIFWidget.movie.setScaledSize(self.gifSize * self.gifScale / 50)
            self.movie.start()
        layout.addWidget(self.preview, 8, 0, 4, 7)

        self.testButton = QPushButton('预览效果')
        self.testButton.clicked.connect(self.testAnimate)
        self.testButton.setFixedSize(205, 65)
        layout.addWidget(self.testButton, 12, 0, 2, 3)

        self.startButton = QPushButton('开始捕获')
        self.startButton.clicked.connect(self.startMonitor)
        self.startButton.setFixedSize(205, 65)
        layout.addWidget(self.startButton, 12, 4, 2, 3)

        self.resizeTimer = QTimer()
        self.resizeTimer.setInterval(16)
        self.resizeTimer.timeout.connect(self.resizeGIFWidget)
        self.resizeTimer.start()

        self.widgetsList = [
            self.roomURLEdit, self.presetCombobox, self.giftEdit,
            self.defaultWordsButton, self.wordsEdit, self.fontButton,
            self.outLineButton, self.outLineSizeBar, self.bgmButton,
            self.volumeBar, self.animeSecondComboBox, self.scaledBar,
            self.advancedButton, self.preview, self.testButton,
            self.outLineSizeLabel, self.volumeLabel, self.scaledValue,
            self.animeSecond, self.bgmEdit, self.roomIDLabel,
            self.biliLiveLabel, self.fontLabel, self.outLineLabel
        ]

    def resizeGIFWidget(self):
        self.GIFWidget.resize(300, 200)
        self.resize(540, 600)
        w, h = self.GIFWidget.width(), self.GIFWidget.height()
        x, y = self.GIFWidget.pos().x(), self.GIFWidget.pos().y()
        currentCenterPos = QPoint(x + w / 2, y + h / 2)
        self.GIFWidget.move(self.GIFWidget.pos() - currentCenterPos +
                            self.GIFWidgetCenterPos)

    def changePreset(self, index):
        if index == 9:
            self.giftEdit.setEnabled(False)
        else:
            self.giftEdit.setEnabled(True)
        self.presetIndex = str(index)
        self.gift = self.config[self.presetIndex]['gift']
        self.giftEdit.setText(self.gift)
        self.wordsEdit.setText(self.config[self.presetIndex]['words'])

        self.second = self.config[self.presetIndex]['second']
        self.animeSecondComboBox.setCurrentIndex(self.second - 1)
        self.GIFWidget.setSecond(self.second)
        self.color = self.config[self.presetIndex]['font_color']

        fontInfo = '%s  %s  %s  ' % (
            self.config[self.presetIndex]['font_name'],
            self.config[self.presetIndex]['font_size'],
            self.config[self.presetIndex]['font_color'])
        self.font = QFont(self.config[self.presetIndex]['font_name'],
                          self.config[self.presetIndex]['font_size'])
        if self.config[self.presetIndex]['font_bold']:
            self.font.setBold(self.config[self.presetIndex]['font_bold'])
            fontInfo += '加粗  '
        if self.config[self.presetIndex]['font_italic']:
            self.font.setItalic(self.config[self.presetIndex]['font_italic'])
            fontInfo += '斜体'
        self.fontLabel.setText(fontInfo)
        self.fontLabel.setStyleSheet('color:' + self.color)
        self.GIFWidget.setFont(self.font)
        self.GIFWidget.showText.setBrush(QColor(self.color))

        self.outColor = self.config[self.presetIndex]['out_color']

        self.config[self.presetIndex]['out_color'] = self.outColor
        self.GIFWidget.showText.setPen(self.outColor)
        self.GIFWidget.showText.repaint()
        self.outLineLabel.setText(self.outColor)
        self.outLineLabel.setStyleSheet('color:' + self.outColor)

        self.outSize = self.config[self.presetIndex]['out_size']

        self.outLineSizeBar.setValue(self.outSize)
        self.config[self.presetIndex]['out_size'] = self.outSize
        self.GIFWidget.showText.w = self.outSize / 250
        self.GIFWidget.showText.repaint()

        self.preview.clear()
        self.GIFWidget.showGIF.clear()
        self.preview.setText('点击或拖入要播放的答谢gif动图')
        if self.config[self.presetIndex]['gif_path']:
            self.movie = self.movieList[index]
            self.gifSize = self.gifSizeList[index]
            pos = self.config[self.presetIndex]['gif_scale']
            self.scaledBar.setValue(pos)
            if self.gifSize:
                self.movie.setScaledSize(self.gifSize * pos / 50)
            self.preview.setMovie(self.movie)
            self.GIFWidget.showGIF.setMovie(self.movie)
            self.movie.start()

        self.bgmEdit.setText(
            os.path.split(self.config[self.presetIndex]['bgm_path'])[1])
        self.sound.setMedia(
            QUrl.fromLocalFile(self.config[self.presetIndex]['bgm_path']))

        self.volume = self.config[self.presetIndex]['volume']
        self.volumeBar.setValue(self.volume)
        self.sound.setVolume(self.volume)

    def setURL(self, text):
        self.config['room_url'] = text

    def setWords(self, text):
        if self.presetIndex == '9':
            self.GIFWidget.setText(text, 'captain')
        else:
            self.GIFWidget.setText(text, 'gift')
        self.config[self.presetIndex]['words'] = text

    def setDefaultWords(self):
        if self.presetIndex == '9':
            text = '恭迎 {用户} 上舰~~~'
            self.GIFWidget.setText(text, 'captain')
        else:
            text = '感谢 {用户} 投喂的{数量}个{礼物}~'
            self.GIFWidget.setText(text, 'gift')
        self.wordsEdit.setText(text)
        self.config[self.presetIndex]['words'] = text

    def changeGift(self):
        self.config[self.presetIndex]['gift'] = self.giftEdit.text()

    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(os.path.split(filePath)[1])
            self.sound.setMedia(QUrl.fromLocalFile(filePath))
            self.config[self.presetIndex]['bgm_path'] = filePath

    def changevolume(self, p):
        pos = p.x() / self.volumeBar.width() * 100
        if pos > 100:
            pos = 100
        elif pos < 0:
            pos = 0
        self.volumeBar.setValue(pos)
        self.volume = pos
        self.sound.setVolume(pos)
        self.config[self.presetIndex]['volume'] = pos

    def selectBackgroundColor(self, color):
        self.config['background_color'] = color
        self.GIFWidget.setBackgroundColor(color)

    def setTop(self, topToken):
        self.config['top'] = topToken

    def setopacity(self, opacityToken):
        self.config['opacity'] = opacityToken

    def setSecond(self, index):
        self.second = index + 1
        self.GIFWidget.setSecond(self.second)
        self.config[self.presetIndex]['second'] = self.second

    def scaleChange(self, p):
        pos = p.x() / self.scaledBar.width() * 100
        if pos > 100:
            pos = 100
        elif pos < 1:
            pos = 1
        self.scaledBar.setValue(pos)
        self.config[self.presetIndex]['gif_scale'] = pos
        scale = pos / 50
        if self.gifSize:
            self.movie.setScaledSize(self.gifSize * scale)
            # self.GIFWidget.movie.setScaledSize(self.gifSize * scale)

    def sizeChange(self, p):
        self.outSize = p.x() / self.outLineSizeBar.width() * 100
        if self.outSize > 100:
            self.outSize = 100
        elif self.outSize < 1:
            self.outSize = 1
        self.outLineSizeBar.setValue(self.outSize)
        self.config[self.presetIndex]['out_size'] = self.outSize
        self.GIFWidget.showText.w = self.outSize / 400
        self.GIFWidget.showText.repaint()

    def click(self):
        filePath = QFileDialog.getOpenFileName(self, "请选择gif文件", 'gif',
                                               "*.gif;;所有文件 *.*")[0]
        if filePath:
            self.openFile(filePath)
        else:
            self.preview.clear()
            self.GIFWidget.showGIF.clear()
            self.preview.setText('点击或拖入要播放的答谢gif动图')
            self.config[self.presetIndex]['gif_path'] = ''

    def openFile(self, filePath):
        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')
        self.gifSize = QPixmap(filePath).size()
        index = self.presetCombobox.currentIndex()
        self.movieList[index] = QMovie(filePath)
        self.movie = self.movieList[index]
        self.preview.setMovie(self.movie)
        self.GIFWidget.showGIF.setMovie(self.movie)
        self.movie.start()
        # self.GIFWidget.setGIFPath(filePath)
        self.config[self.presetIndex]['gif_path'] = r'%s/gif/%s' % (
            os.getcwd(), fileName)
        self.scaledBar.setValue(50)

    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.option.close()
        with codecs.open('utils/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[self.presetIndex]['font_name'] = fontName
            self.config[self.presetIndex]['font_size'] = fontSize
            self.config[self.presetIndex]['font_bold'] = fontBold
            self.config[self.presetIndex]['font_italic'] = fontItalic
            self.GIFWidget.setFont(self.font)
            fontInfo = '%s  %s  %s  ' % (
                self.config[self.presetIndex]['font_name'],
                self.config[self.presetIndex]['font_size'],
                self.config[self.presetIndex]['font_color'])
            if fontBold:
                fontInfo += '加粗  '
            if fontItalic:
                fontInfo += '斜体'
            self.fontLabel.setText(fontInfo)
            self.fontLabel.setStyleSheet('color:' + self.color)
        color = QColorDialog.getColor(self.color)
        if color.isValid():
            self.color = color.name()
            self.config[self.presetIndex]['font_color'] = self.color
            self.GIFWidget.showText.setBrush(QColor(self.color))
            self.GIFWidget.showText.repaint()

    def setOutLine(self):
        color = QColorDialog().getColor(self.outColor)
        if color.isValid():
            self.outColor = color.name()
            self.config[self.presetIndex]['out_color'] = self.outColor
            self.GIFWidget.showText.setPen(self.outColor)
            self.GIFWidget.showText.repaint()
            self.outLineLabel.setText(self.outColor)
            self.outLineLabel.setStyleSheet('color:' + self.outColor)

    def setConfig(self, config, mode, index):
        self.GIFWidget.setText(config['words'], mode)

        # self.movie = self.movieList[index]
        # self.gifSize = self.gifSizeList[index]
        # if self.gifSize:
        #     self.movie.setScaledSize(self.gifSize * config['gif_scale'] / 50)
        # self.GIFWidget.showGIF.setMovie(self.movie)
        # self.movie.start()

        self.GIFWidget.showGIF.clear()
        movie = self.movieList[index]
        gifSize = self.gifSizeList[index]
        if gifSize:
            movie.setScaledSize(gifSize * config['gif_scale'] / 50)
        self.GIFWidget.showGIF.setMovie(movie)
        # self.GIFWidget.movie = QMovie(config['gif_path'])
        # self.gifSize = QPixmap(config['gif_path']).size()
        # if self.gifSize:
        #     self.GIFWidget.movie.setScaledSize(self.gifSize * config['gif_scale'] / 50)
        # self.GIFWidget.showGIF.setMovie(self.GIFWidget.movie)
        # self.GIFWidget.movie.start()
        self.GIFWidget.setSecond(config['second'])
        self.GIFWidget.showText.setBrush(QColor(config['font_color']))
        self.GIFWidget.showText.setPen(config['out_color'])
        self.GIFWidget.showText.w = config['out_size'] / 400
        self.GIFWidget.showText.repaint()
        font = QFont(config['font_name'], config['font_size'])
        if config['font_bold']:
            font.setBold(True)
        if config['font_italic']:
            font.setItalic(True)
        self.GIFWidget.setFont(font)

    def testAnimate(self):
        if self.bgmEdit.text():
            self.sound.stop()
            self.sound.play()
        self.GIFWidget.frame = self.second * 60
        self.GIFWidget.animationTimer.start()

    def playAnimate(self, giftInfo):
        uid, num, gift = giftInfo
        self.GIFWidget.ID = uid
        self.GIFWidget.number = str(num)
        self.GIFWidget.gift = gift
        self.GIFWidget.gifOpacity.setOpacity(0)
        self.GIFWidget.textOpacity.setOpacity(0)
        if gift == 'captain':
            self.setConfig(self.config['9'], 'captain', 9)
            self.GIFWidget.animationTimer.start()
            presetIndex = '9'
        else:
            for presetIndex in ['8', '7', '6', '5', '4', '3', '2', '1', '0']:
                if gift in self.config[presetIndex]['gift']:
                    self.setConfig(self.config[presetIndex], 'gift',
                                   int(presetIndex))
                    self.GIFWidget.animationTimer.start()
                    break
        bgm = self.config[presetIndex]['bgm_path']
        if bgm:
            # if bgm != self.oldBGM:
            #     self.oldBGM = bgm
            self.sound.setMedia(QUrl.fromLocalFile(bgm))
            self.sound.setVolume(self.config[presetIndex]['volume'])
            self.sound.play()

    def popOption(self):
        self.option.hide()
        self.option.show()

    def animateFinish(self):
        self.sound.stop()

    def changeCenter(self, qpoint):
        self.GIFWidgetCenterPos += qpoint

    def startMonitor(self):
        if not self.executeToken:
            self.remoteThread = remoteThread(self.config['room_url'])
            self.remoteThread.giftInfo.connect(self.playAnimate)
            self.remoteThread.start()
            for widget in self.widgetsList:
                widget.setEnabled(False)
            self.executeToken = True
            self.GIFWidget.executeToken = True
            self.GIFWidget.gifOpacity.setOpacity(0)
            self.GIFWidget.textOpacity.setOpacity(0)
            self.startButton.setStyleSheet('background-color:#3daee9')
            self.startButton.setText('停止捕获')
        else:
            self.sound.stop()
            self.GIFWidget.animationTimer.stop()

            self.GIFWidget.showGIF.clear()
            self.GIFWidget.showGIF.setMovie(self.movie)

            self.remoteThread.terminate()
            self.remoteThread.quit()
            self.remoteThread.wait()
            for widget in self.widgetsList:
                widget.setEnabled(True)
            self.executeToken = False
            self.GIFWidget.executeToken = False
            self.GIFWidget.gifOpacity.setOpacity(1)
            self.GIFWidget.textOpacity.setOpacity(1)
            self.startButton.setStyleSheet('background-color:#31363b')
            self.startButton.setText('开始捕获')
            text = self.wordsEdit.text()
            if self.presetIndex == '9':
                self.GIFWidget.setText(text, 'captain', True)
            else:
                self.GIFWidget.setText(text, 'gift', True)
Beispiel #15
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.PLAY_Button.clicked.connect(self.PLAY)
        self.ui.PAUSE_Button.clicked.connect(self.PAUSE)
        self.ui.STOP_Button.clicked.connect(self.STOP)
        self.ui.PREV_Button.clicked.connect(self.PREV)
        self.ui.NEXT_Button.clicked.connect(self.NEXT)
        self.ui.next_file_button.clicked.connect(self.nextFile)
        self.ui.del_file_button.clicked.connect(self.delFile)
        self.ui.dial_volumen.setMinimum(0)
        self.ui.dial_volumen.setMaximum(100)
        self.ui.dial_volumen.setValue(3)
        self.ui.volumen_level.setText(str(self.ui.dial_volumen.value()) + '%')

        self.ui.sliderTime.setMinimum(0)
        self.ui.sliderTime.setMaximum(3600)
        self.ui.sliderTime.setValue(0)
        self.ui.timePlayed.setText(str(self.ui.sliderTime.value()) + 's')

        self.mediaPlayer = QMediaPlayer()
        self.mediaPlayer.setVideoOutput(self.ui.wVideo)
        #mediaContent = QMediaContent(QUrl.fromLocalFile('big_buck_bunny.avi'))
        #self.mediaPlayer.setMedia(mediaContent)
        #Dialog
        self.ui.dial_volumen.valueChanged.connect(self.changeVolDial)
        self.mediaPlayer.positionChanged.connect(self.updateTime)
        self.ui.sliderTime.valueChanged.connect(self.changeTime)
        self.ui.file_list.itemDoubleClicked.connect(self.loadfile)

    def changeVolDial(self):
        print('VOLUMEN CHANGED')
        self.ui.volumen_level.setText(str(self.ui.dial_volumen.value()) + '%')
        self.mediaPlayer.setVolume(self.ui.dial_volumen.value())

    def updateTime(self):
        self.ui.sliderTime.valueChanged.disconnect(self.changeTime)
        localTime = QTime(0, 0, 0)
        currentTime = localTime.addMSecs(self.mediaPlayer.position())
        #print(self.mediaPlayer.position()-self.mediaPlayer.duration())
        timeLeft = localTime.addMSecs(self.mediaPlayer.duration() -
                                      self.mediaPlayer.position())
        #h, res = divmod(t, 3600)
        #m, s = divmod(res, 60)
        #time_str = f'{int(h):02}:{int(m):02}:{int(s):02}'
        self.ui.timePlayed.setText(currentTime.toString("HH:mm:ss"))
        self.ui.timeTotal.setText('-' + timeLeft.toString("HH:mm:ss"))
        self.ui.sliderTime.setValue(self.mediaPlayer.position())
        self.ui.sliderTime.valueChanged.connect(self.changeTime)

    def loadfile(self):
        #rowItem=self.ui.file_list.currentRow()
        currentItem = self.ui.file_list.currentItem()
        print(self.ui.file_list.currentItem().text())
        #mediaContent=QMediaContent(QUrl.fromLocalFile(currentItem.toolTip()))
        mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.text()))
        #mediaContent = QMediaContent(QUrl.fromLocalFile('big_buck_bunny.avi'))
        self.mediaPlayer.setMedia(mediaContent)
        self.PLAY()
        #print(self.ui.file_list.takeItem(0))

    def changeTime(self):
        self.mediaPlayer.positionChanged.disconnect(self.updateTime)
        print('Time CHANGED')
        self.mediaPlayer.setPosition(self.ui.sliderTime.value())
        localTime = QTime(0, 0, 0)
        currentTime = localTime.addMSecs(self.mediaPlayer.position())
        self.ui.timePlayed.setText(currentTime.toString("HH:mm:ss"))
        self.mediaPlayer.positionChanged.connect(self.updateTime)

    def delFile(self):
        print('delFile PRESSED')
        rowItem = self.ui.file_list.currentRow()
        if rowItem != -1:
            self.ui.file_list.takeItem(rowItem)

    def nextFile(self):
        print('nextFile PRESSED')
        filename = QFileDialog.getOpenFileName(self, "Choix Film")
        item = QListWidgetItem(filename[0])
        self.ui.file_list.addItem(item)

    def PLAY(self):
        print('PLAY PRESSED')
        self.mediaPlayer.setVolume(self.ui.dial_volumen.value())
        self.mediaPlayer.play()
        localTime = QTime(0, 0, 0)
        totalTime = localTime.addMSecs(self.mediaPlayer.duration())
        self.ui.sliderTime.setMaximum(self.mediaPlayer.duration())
        self.ui.timeTotal.setText(totalTime.toString("HH:mm:ss"))

    def PAUSE(self):
        print('PAUSE PRESSED')
        if self.mediaPlayer.state() == QMediaPlayer.PausedState:
            self.mediaPlayer.play()
        else:
            self.mediaPlayer.pause()

    def PREV(self):
        print('PREV PRESSED')
        rowItem = self.ui.file_list.currentRow()
        if rowItem == -1:
            return
        else:
            self.ui.file_list.setCurrentRow((rowItem - 1))
            filename = self.ui.file_list.currentItem().text()
            print('Loading ' + filename)
            mediaContent = QMediaContent(QUrl.fromLocalFile(filename))
            self.mediaPlayer.setMedia(mediaContent)
            self.PLAY()

    def NEXT(self):
        print('NEXT PRESSED')
        totalItems = self.ui.file_list.count()
        rowItem = self.ui.file_list.currentRow()

        if rowItem + 1 > totalItems:
            return
        else:
            self.ui.file_list.setCurrentRow((rowItem + 1))
            filename = self.ui.file_list.currentItem().text()
            print('Loading ' + filename)
            mediaContent = QMediaContent(QUrl.fromLocalFile(filename))
            self.mediaPlayer.setMedia(mediaContent)
            self.PLAY()

    def STOP(self):
        print('STOP PRESSED')
        self.mediaPlayer.stop()

    def get_str_time(t):
        h, res = divmod(t, 3600)
        m, s = divmod(res, 60)
        return f'{int(h):02}:{int(m):02}:{int(s):02}'
Beispiel #16
0
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()
Beispiel #17
0
class MainWindow(QObject):

    #class constructor
    def __init__(self, ui_file, parent=None):

        #reference to our music player
        self.music_player = QMediaPlayer()

        self.music_playlist = QMediaPlaylist()
        self.music_player.setVolume(80)

        #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)

        self.window.setWindowFlags(Qt.MSWindowsFixedSizeDialogHint)
        self.window.setWindowTitle("SynthWAV")

        #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)

        open_button = self.window.findChild(QPushButton, 'open_button')
        open_button.clicked.connect(self.open_action_triggered)

        quit_button = self.window.findChild(QPushButton, 'quit_button')
        quit_button.clicked.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)

        progress_slider = self.window.findChild(QSlider, 'progress_slider')
        self.music_player.positionChanged.connect(self.update_progress)
        progress_slider.sliderMoved.connect(self.scrub_progress)

        volume_slider = self.window.findChild(QSlider, 'volume_slider')
        volume_slider.setValue(self.music_player.volume())
        volume_slider.sliderMoved.connect(self.adjust_volume)

        next_button = self.window.findChild(QPushButton, 'next_button')
        next_button.clicked.connect(self.next_button_clicked)

        previous_button = self.window.findChild(QPushButton, 'previous_button')
        previous_button.clicked.connect(self.previous_button_clicked)

        fforward_button = self.window.findChild(QPushButton, 'fforward_button')
        fforward_button.clicked.connect(self.fforward_button_clicked)

        fbackward_button = self.window.findChild(QPushButton,
                                                 'fbackward_button')
        fbackward_button.clicked.connect(self.fbackward_button_clicked)

        self.music_playlist.currentMediaChanged.connect(self.change_title)

        #show window to user
        self.window.show()

    def open_action_triggered(self):
        files = QFileDialog.getOpenFileNames(self.window,
                                             "Add songs to playlist")
        for i in range(len(files[0])):
            self.music_playlist.addMedia(QUrl.fromLocalFile(str(files[0][i])))
        self.music_playlist.setCurrentIndex(0)
        self.music_player.setPlaylist(self.music_playlist)

    def change_title(self):
        title_label = self.window.findChild(QLabel, 'media_title')
        show_title_path = self.music_playlist.currentMedia().canonicalUrl(
        ).fileName()
        show_title = os.path.splitext(show_title_path)
        title_label.setText(show_title[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 next_button_clicked(self):
        self.music_playlist.next()

    def previous_button_clicked(self):
        self.music_playlist.previous()

    def fforward_button_clicked(self):
        self.music_player.setPosition(self.music_player.position() + 10000)

    def fbackward_button_clicked(self):
        self.music_player.setPosition(self.music_player.position() - 10000)

    def update_progress(self):
        progress_slider = self.window.findChild(QSlider, 'progress_slider')

        if self.music_player.duration != 0:
            progress_slider.setMaximum(self.music_player.duration())
            total_sec = (self.music_player.duration() / 1000) % 60
            total_min = (self.music_player.duration() / (1000 * 60)) % 60
            if (total_sec < 10):
                total_time = ("%d:0%d" % (int(total_min), int(total_sec)))
            else:
                total_time = ("%d:%d" % (int(total_min), int(total_sec)))
            track_duration_label = self.window.findChild(
                QLabel, 'track_duration_label')
            track_duration_label.setText(total_time)

        progress = self.music_player.position()
        progress_slider.setValue(progress)
        cur_sec = (self.music_player.position() / 1000) % 60
        cur_min = (self.music_player.position() / (1000 * 60)) % 60
        if (cur_sec < 10):
            cur_time = ("%d:0%d" % (int(cur_min), int(cur_sec)))
        else:
            cur_time = ("%d:%d" % (int(cur_min), int(cur_sec)))
        track_current_label = self.window.findChild(QLabel,
                                                    'track_current_label')
        track_current_label.setText(cur_time)

    def scrub_progress(self):
        progress_slider = self.window.findChild(QSlider, 'progress_slider')
        self.music_player.setPosition(progress_slider.sliderPosition())
        cur_min = (self.music_player.position() / 1000) % 60
        cur_sec = (self.music_player.position() / (1000 * 60)) % 60
        if (cur_sec < 10):
            cur_time = ("%d:0%d" % (int(cur_min), int(cur_sec)))
        else:
            cur_time = ("%d:%d" % (int(cur_min), int(cur_sec)))
        track_current_label = self.window.findChild(QLabel,
                                                    'track_current_label')
        track_current_label.setText(cur_time)

    def adjust_volume(self):
        volume_slider = self.window.findChild(QSlider, 'volume_slider')
        self.music_player.setVolume(volume_slider.sliderPosition())
Beispiel #18
0
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()
Beispiel #19
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.lecture.clicked.connect(self.lectureClicked)
        self.mediaPlayer = QMediaPlayer()
        self.mediaPlayer.setVideoOutput(self.ui.ecran)

        self.ui.pause.clicked.connect(self.pauseClicked)
        self.ui.suivant.clicked.connect(self.suivantClicked)
        self.ui.stop.clicked.connect(self.stopClicked)
        self.ui.precedent.clicked.connect(self.precedentClicked)

        self.ui.dialVol.valueChanged.connect(self.dVol)

        self.ui.slider.sliderMoved.connect(self.sliderMov)

        mediaContent = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi"))
        self.mediaPlayer.setMedia(mediaContent)
        self.mediaPlayer.positionChanged.connect(self.mediaDurationChange)
        self.mediaPlayer.positionChanged.connect(self.mediapositionChange)

    def lectureClicked(self):
        print("Lecture !!!")
        self.mediaPlayer.play()
        #self.sliderMov.connect()

    def pauseClicked(self):
        print("Pause !!!")
        if self.mediaPlayer.state() == QMediaPlayer.PausedState:
            self.mediaPlayer.play()
        else:
            self.mediaPlayer.pause()

    def stopClicked(self):
        print("----------------stooooooop-----------------!")
        self.mediaPlayer.stop()

    def precedentClicked(self):
        print("Précédent !")

    def suivantClicked(self):
        print("Suivant !")

    def sliderMov(self):
        print("Slide .....")
        self.mediaPlayer.setPosition(self.ui.slider.value())

    def onceu(self):
        ttalTimeMedia = self.mediaPlayer.duration()

    def mediaDurationChange(self):
        print("medialoaded")
        mediaDuration = self.mediaPlayer.duration()
        ttalTimeMedia = QTime(0, 0, 0)
        ttalTimeMedia = ttalTimeMedia.addMSecs(mediaDuration)
        self.ui.toBe.setText(ttalTimeMedia.toString("HH:mm:ss"))
        #self.ui.slider.setValue(mediaPosition)

    def mediapositionChange(self):
        mediaPosition = self.mediaPlayer.position()
        currentTimeMedia = QTime(0, 0, 0)
        currentTimeMedia = currentTimeMedia.addMSecs(mediaPosition)

        self.ui.onceU.setText(currentTimeMedia.toString("HH:mm:ss"))
        self.ui.slider.setRange(0, self.mediaPlayer.duration())
        self.ui.slider.setValue(self.mediaPlayer.position())

    def dVol(self):
        self.ui.pourcent.setText(str(self.ui.dialVol.value()) + "%")
        self.mediaPlayer.setVolume(self.ui.dialVol.value())
Beispiel #20
0
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()
Beispiel #21
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pBLecture.clicked.connect(self.lecture)
        self.ui.pBPause.clicked.connect(self.pause)
        self.ui.pBStop.clicked.connect(self.stop)
        self.ui.pBPrecedent.clicked.connect(self.precedent)
        self.ui.pBSuivant.clicked.connect(self.suivant)

        self.ui.pBAjout.clicked.connect(self.ajoutListe)
        self.ui.pBSupp.clicked.connect(self.suppListe)
        self.ui.listWidget.itemDoubleClicked.connect(self.mediaSelected)

        self.ui.dBVolume.valueChanged.connect(self.volume)
        self.ui.dBVolume.setRange(0, 100)
        self.ui.suiviVol.setText(f'{str(self.ui.dBVolume.value())} %')
        self.ui.sTpsCourant.valueChanged.connect(self.avanceSlider)

        self.mediaPlayer = QMediaPlayer()
        self.mediaPlayer.setVideoOutput(self.ui.Lecteur)

        self.mediaPlayer.durationChanged.connect(self.duree)
        self.mediaPlayer.positionChanged.connect(self.avancee)

        # mediaContent = QMediaContent(QUrl.fromLocalFile("big_buck_bunny.avi"))
        # self.mediaPlayer.setMedia(mediaContent)

    def lecture(self):
        print("Lecture")
        if self.mediaPlayer.state() == QMediaPlayer.StoppedState:
            self.mediaSelected()
        else:
            self.mediaPlayer.play()

    def pause(self):
        print("Pause")
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def stop(self):
        print("Stop")
        self.mediaPlayer.stop()

    def precedent(self):
        currentItemRow = self.ui.listWidget.currentRow()
        if currentItemRow == -1:
            return
        totalItems = self.ui.listWidget.count()
        self.ui.listWidget.setCurrentRow((currentItemRow - 1) % totalItems)
        self.mediaSelected()
        print("Précédent")

    def suivant(self):
        currentItemRow = self.ui.listWidget.currentRow()
        if currentItemRow == -1:
            return
        totalItems = self.ui.listWidget.count()
        self.ui.listWidget.setCurrentRow((currentItemRow + 1) % totalItems)
        self.mediaSelected()
        print("Suivant")

    # def ajoutListe (self):
    #     print("Ajout dans playlist")
    #     newFile=QFileDialog.getOpenFileName(self, "Choix Film", "/home", "Movie Files (*.avi, *.mp4)")
    #     newMovie=QListWidgetItem(newFile[0])
    #     self.ui.listWidget.addItem(newMovie)

    def ajoutListe(self):
        print("Ajout dans playlist")
        newFile = QFileDialog.getOpenFileName(self, "Choix Film", "/home",
                                              "Movie Files (*.avi, *.mp4)")
        fInfo = QFileInfo(newFile[0])
        fShortName = fInfo.baseName()
        newMovie = QListWidgetItem(fShortName)
        newMovie.setToolTip(newFile[0])
        self.ui.listWidget.addItem(newMovie)

    def suppListe(self):
        print("Supprimer de playList")
        rowItem = self.ui.listWidget.currentRow()
        if rowItem != -1:
            self.ui.listWidget.takeItem(rowItem)

    # def mediaSelected (self):
    #     currentItem = self.ui.listWidget.currentItem()
    #     mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.text()))
    #     self.mediaPlayer.setMedia(mediaContent)
    #     self.lecture()

    def mediaSelected(self):
        currentItem = self.ui.listWidget.currentItem()
        mediaContent = QMediaContent(QUrl.fromLocalFile(currentItem.toolTip()))
        self.mediaPlayer.setMedia(mediaContent)
        self.mediaPlayer.play()

    def volume(self):
        self.mediaPlayer.setVolume(self.ui.dBVolume.value())
        self.ui.suiviVol.setText(f'{str(self.ui.dBVolume.value())} %')

    def duree(self):
        mediaDuration = self.mediaPlayer.duration()
        self.ui.sTpsCourant.setRange(0, mediaDuration)
        totalTimeMedia = QTime(0, 0, 0)
        totalTimeMedia = totalTimeMedia.addMSecs(mediaDuration)
        self.ui.lRestantTps.setText(totalTimeMedia.toString("HH:mm:ss"))

    def avancee(self):
        self.ui.sTpsCourant.valueChanged.disconnect(self.avanceSlider)
        mediaPosition = self.mediaPlayer.position()
        currentTimeMedia = QTime(0, 0, 0)
        currentTimeMedia = currentTimeMedia.addMSecs(mediaPosition)
        self.ui.lAvanceeTps.setText(currentTimeMedia.toString("HH:mm:ss"))
        self.ui.sTpsCourant.setValue(mediaPosition)
        self.ui.sTpsCourant.valueChanged.connect(self.avanceSlider)

    def avanceSlider(self):
        self.mediaPlayer.positionChanged.disconnect(self.avancee)
        self.mediaPlayer.setPosition(self.ui.sTpsCourant.sliderPosition())
        self.mediaPlayer.positionChanged.connect(self.avancee)
Beispiel #22
0
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)
Beispiel #23
0
class VideoPlayer(QWidget):
    def __init__(self, aPath, parent=None):
        super(VideoPlayer, self).__init__(parent)

        self.setAttribute(Qt.WA_NoSystemBackground, True)
        self.setAcceptDrops(True)
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.StreamPlayback)
        self.mediaPlayer.mediaStatusChanged.connect(self.printMediaData)
        self.mediaPlayer.setVolume(80)
        self.videoWidget = QVideoWidget(self)

        self.lbl = QLineEdit('00:00:00')
        self.lbl.setReadOnly(True)
        self.lbl.setFixedWidth(70)
        self.lbl.setUpdatesEnabled(True)
        self.lbl.setStyleSheet(stylesheet(self))
        self.lbl.selectionChanged.connect(lambda: self.lbl.setSelection(0, 0))

        self.elbl = QLineEdit('00:00:00')
        self.elbl.setReadOnly(True)
        self.elbl.setFixedWidth(70)
        self.elbl.setUpdatesEnabled(True)
        self.elbl.setStyleSheet(stylesheet(self))
        self.elbl.selectionChanged.connect(
            lambda: self.elbl.setSelection(0, 0))

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setFixedWidth(32)
        self.playButton.setStyleSheet("background-color: black")
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal, self)
        self.positionSlider.setStyleSheet(stylesheet(self))
        self.positionSlider.setRange(0, 100)
        self.positionSlider.sliderMoved.connect(self.setPosition)
        self.positionSlider.setSingleStep(2)
        self.positionSlider.setPageStep(20)
        self.positionSlider.setAttribute(Qt.WA_TranslucentBackground, True)

        self.clip = QApplication.clipboard()
        self.process = QProcess(self)
        self.process.readyRead.connect(self.dataReady)
        self.process.finished.connect(self.playFromURL)

        self.myurl = ""

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(5, 0, 5, 0)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.lbl)
        controlLayout.addWidget(self.positionSlider)
        controlLayout.addWidget(self.elbl)

        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.videoWidget)
        layout.addLayout(controlLayout)

        self.setLayout(layout)

        self.myinfo = "©2016\nAxel Schneider\n\nMouse Wheel = Zoom\nUP = Volume Up\nDOWN = Volume Down\n" + \
                "LEFT = < 1 Minute\nRIGHT = > 1 Minute\n" + \
                "SHIFT+LEFT = < 10 Minutes\nSHIFT+RIGHT = > 10 Minutes"

        self.widescreen = True

        #### shortcuts ####
        self.shortcut = QShortcut(QKeySequence("q"), self)
        self.shortcut.activated.connect(self.handleQuit)
        self.shortcut = QShortcut(QKeySequence("u"), self)
        self.shortcut.activated.connect(self.playFromURL)

        self.shortcut = QShortcut(QKeySequence("y"), self)
        self.shortcut.activated.connect(self.getYTUrl)

        self.shortcut = QShortcut(QKeySequence("o"), self)
        self.shortcut.activated.connect(self.openFile)
        self.shortcut = QShortcut(QKeySequence(" "), self)
        self.shortcut.activated.connect(self.play)
        self.shortcut = QShortcut(QKeySequence("f"), self)
        self.shortcut.activated.connect(self.handleFullscreen)
        self.shortcut = QShortcut(QKeySequence("i"), self)
        self.shortcut.activated.connect(self.handleInfo)
        self.shortcut = QShortcut(QKeySequence("s"), self)
        self.shortcut.activated.connect(self.toggleSlider)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Right), self)
        self.shortcut.activated.connect(self.forwardSlider)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Left), self)
        self.shortcut.activated.connect(self.backSlider)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Up), self)
        self.shortcut.activated.connect(self.volumeUp)
        self.shortcut = QShortcut(QKeySequence(Qt.Key_Down), self)
        self.shortcut.activated.connect(self.volumeDown)
        self.shortcut = QShortcut(
            QKeySequence(Qt.ShiftModifier + Qt.Key_Right), self)
        self.shortcut.activated.connect(self.forwardSlider10)
        self.shortcut = QShortcut(QKeySequence(Qt.ShiftModifier + Qt.Key_Left),
                                  self)
        self.shortcut.activated.connect(self.backSlider10)

        self.mediaPlayer.setVideoOutput(self.videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)

        print("QT5 Player started")
        print("press 'o' to open file (see context menu for more)")
        self.suspend_screensaver()

    def mouseDoubleClickEvent(self, event):
        self.handleFullscreen()

    def playFromURL(self):
        self.mediaPlayer.pause()
        self.myurl = self.clip.text()
        self.mediaPlayer.setMedia(QMediaContent(QUrl(self.myurl)))
        self.playButton.setEnabled(True)
        self.mediaPlayer.play()
        self.hideSlider()
        print(self.myurl)

    def getYTUrl(self):
        cmd = "youtube-dl -g -f best " + self.clip.text()
        print("grabbing YouTube URL")
        self.process.start(cmd)

    def dataReady(self):
        self.myurl = str(self.process.readAll(), encoding='utf8').rstrip()  ###
        self.myurl = self.myurl.partition("\n")[0]
        print(self.myurl)
        self.clip.setText(self.myurl)
        self.playFromURL()

    def suspend_screensaver(self):
        'suspend linux screensaver'
        proc = subprocess.Popen(
            'gsettings set org.gnome.desktop.screensaver idle-activation-enabled false',
            shell=True)
        proc.wait()

    def resume_screensaver(self):
        'resume linux screensaver'
        proc = subprocess.Popen(
            'gsettings set org.gnome.desktop.screensaver idle-activation-enabled true',
            shell=True)
        proc.wait()

    def openFile(self):
        fileName, _ = QFileDialog.getOpenFileName(
            self, "Open Movie",
            QDir.homePath() + "/Videos",
            "Media (*.webm *.mp4 *.ts *.avi *.mpeg *.mpg *.mkv *.VOB *.m4v *.3gp *.mp3 *.m4a *.wav *.ogg *.flac *.m3u *.m3u8)"
        )

        if fileName != '':
            self.loadFilm(fileName)
            print("File loaded")

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)
        mtime = QTime(0, 0, 0, 0)
        mtime = mtime.addMSecs(self.mediaPlayer.position())
        self.lbl.setText(mtime.toString())

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)
        mtime = QTime(0, 0, 0, 0)
        mtime = mtime.addMSecs(self.mediaPlayer.duration())
        self.elbl.setText(mtime.toString())

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        print("Error: ", self.mediaPlayer.errorString())

    def handleQuit(self):
        self.mediaPlayer.stop()
        self.resume_screensaver()
        print("Goodbye ...")
        app.quit()

    def contextMenuRequested(self, point):
        menu = QMenu()
        actionFile = menu.addAction(QIcon.fromTheme("video-x-generic"),
                                    "open File (o)")
        actionclipboard = menu.addSeparator()
        actionURL = menu.addAction(QIcon.fromTheme("browser"),
                                   "URL from Clipboard (u)")
        actionclipboard = menu.addSeparator()
        actionYTurl = menu.addAction(QIcon.fromTheme("youtube"),
                                     "URL from YouTube (y)")
        actionclipboard = menu.addSeparator()
        actionToggle = menu.addAction(QIcon.fromTheme("next"),
                                      "show / hide Slider (s)")
        actionFull = menu.addAction(QIcon.fromTheme("view-fullscreen"),
                                    "Fullscreen (f)")
        action169 = menu.addAction(QIcon.fromTheme("tv-symbolic"), "16 : 9")
        action43 = menu.addAction(QIcon.fromTheme("tv-symbolic"), "4 : 3")
        actionSep = menu.addSeparator()
        actionInfo = menu.addAction(QIcon.fromTheme("help-about"), "Info (i)")
        action5 = menu.addSeparator()
        actionQuit = menu.addAction(QIcon.fromTheme("application-exit"),
                                    "Exit (q)")

        actionFile.triggered.connect(self.openFile)
        actionQuit.triggered.connect(self.handleQuit)
        actionFull.triggered.connect(self.handleFullscreen)
        actionInfo.triggered.connect(self.handleInfo)
        actionToggle.triggered.connect(self.toggleSlider)
        actionURL.triggered.connect(self.playFromURL)
        actionYTurl.triggered.connect(self.getYTUrl)
        action169.triggered.connect(self.screen169)
        action43.triggered.connect(self.screen43)
        menu.exec_(self.mapToGlobal(point))

    def wheelEvent(self, event):
        mwidth = self.frameGeometry().width()
        mheight = self.frameGeometry().height()
        mleft = self.frameGeometry().left()
        mtop = self.frameGeometry().top()
        mscale = event.angleDelta().y() / 5
        if self.widescreen == True:
            self.setGeometry(mleft, mtop, mwidth + mscale,
                             round((mwidth + mscale) / 1.778))
        else:
            self.setGeometry(mleft, mtop, mwidth + mscale,
                             round((mwidth + mscale) / 1.33))
        #elif self.positionSlider.hasFocus():
        #    self.positionSlider.value = self.positionSlider.value + 5

    def screen169(self):
        self.widescreen = True
        mwidth = self.frameGeometry().width()
        mheight = self.frameGeometry().height()
        mleft = self.frameGeometry().left()
        mtop = self.frameGeometry().top()
        mratio = 1.778
        self.setGeometry(mleft, mtop, mwidth, round(mwidth / mratio))

    def screen43(self):
        self.widescreen = False
        mwidth = self.frameGeometry().width()
        mheight = self.frameGeometry().height()
        mleft = self.frameGeometry().left()
        mtop = self.frameGeometry().top()
        mratio = 1.33
        self.setGeometry(mleft, mtop, mwidth, round(mwidth / mratio))

    def handleFullscreen(self):
        if self.windowState() & Qt.WindowFullScreen:
            QApplication.setOverrideCursor(Qt.ArrowCursor)
            self.showNormal()
            print("no Fullscreen")
        else:
            self.showFullScreen()
            QApplication.setOverrideCursor(Qt.BlankCursor)
            print("Fullscreen entered")

    def handleInfo(self):
        msg = QMessageBox.about(self, "QT5 Player", self.myinfo)

    def toggleSlider(self):
        if self.positionSlider.isVisible():
            self.hideSlider()
        else:
            self.showSlider()

    def hideSlider(self):
        self.playButton.hide()
        self.lbl.hide()
        self.positionSlider.hide()
        self.elbl.hide()
        mwidth = self.frameGeometry().width()
        mheight = self.frameGeometry().height()
        mleft = self.frameGeometry().left()
        mtop = self.frameGeometry().top()
        if self.widescreen == True:
            self.setGeometry(mleft, mtop, mwidth, round(mwidth / 1.778))
        else:
            self.setGeometry(mleft, mtop, mwidth, round(mwidth / 1.33))

    def showSlider(self):
        self.playButton.show()
        self.lbl.show()
        self.positionSlider.show()
        self.elbl.show()
        mwidth = self.frameGeometry().width()
        mheight = self.frameGeometry().height()
        mleft = self.frameGeometry().left()
        mtop = self.frameGeometry().top()
        if self.widescreen == True:
            self.setGeometry(mleft, mtop, mwidth, round(mwidth / 1.55))
        else:
            self.setGeometry(mleft, mtop, mwidth, round(mwidth / 1.33))

    def forwardSlider(self):
        self.mediaPlayer.setPosition(self.mediaPlayer.position() + 1000 * 60)

    def forwardSlider10(self):
        self.mediaPlayer.setPosition(self.mediaPlayer.position() + 10000 * 60)

    def backSlider(self):
        self.mediaPlayer.setPosition(self.mediaPlayer.position() - 1000 * 60)

    def backSlider10(self):
        self.mediaPlayer.setPosition(self.mediaPlayer.position() - 10000 * 60)

    def volumeUp(self):
        self.mediaPlayer.setVolume(self.mediaPlayer.volume() + 10)
        print("Volume: " + str(self.mediaPlayer.volume()))

    def volumeDown(self):
        self.mediaPlayer.setVolume(self.mediaPlayer.volume() - 10)
        print("Volume: " + str(self.mediaPlayer.volume()))

    def mousePressEvent(self, evt):
        self.oldPos = evt.globalPos()

    def mouseMoveEvent(self, evt):
        delta = QPoint(evt.globalPos() - self.oldPos)
        self.move(self.x() + delta.x(), self.y() + delta.y())
        self.oldPos = evt.globalPos()

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.accept()
        elif event.mimeData().hasText():
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        print("drop")
        if event.mimeData().hasUrls():
            url = event.mimeData().urls()[0].toString()
            print("url = ", url)
            self.mediaPlayer.stop()
            self.mediaPlayer.setMedia(QMediaContent(QUrl(url)))
            self.playButton.setEnabled(True)
            self.mediaPlayer.play()
        elif event.mimeData().hasText():
            mydrop = event.mimeData().text()
            ### YouTube url
            if "youtube" in mydrop:
                print("is YouTube", mydrop)
                self.clip.setText(mydrop)
                self.getYTUrl()
            else:
                ### normal url
                print("generic url = ", mydrop)
                self.mediaPlayer.setMedia(QMediaContent(QUrl(mydrop)))
                self.playButton.setEnabled(True)
                self.mediaPlayer.play()
                self.hideSlider()

    def loadFilm(self, f):
        self.mediaPlayer.setMedia(QMediaContent(QUrl.fromLocalFile(f)))
        self.playButton.setEnabled(True)
        self.mediaPlayer.play()

    def printMediaData(self):
        if self.mediaPlayer.mediaStatus() == 6:
            if self.mediaPlayer.isMetaDataAvailable():
                res = str(self.mediaPlayer.metaData("Resolution")).partition(
                    "PyQt5.QtCore.QSize(")[2].replace(", ",
                                                      "x").replace(")", "")
                print("%s%s" % ("Video Resolution = ", res))
                if int(res.partition("x")[0]) / int(
                        res.partition("x")[2]) < 1.5:
                    self.screen43()
                else:
                    self.screen169()
            else:
                print("no metaData available")

    def openFileAtStart(self, filelist):
        matching = [s for s in filelist if ".myformat" in s]
        if len(matching) > 0:
            self.loadFilm(matching)
Beispiel #24
0
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)
Beispiel #25
0
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
Beispiel #26
0
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()
Beispiel #27
0
class Channel(QObject):
    def __init__(self,
                 name: T.Optional[str],
                 parent: T.Optional[QObject] = None) -> None:
        super().__init__(parent)
        self.name = name
        self.slider_volume: Number = 100
        self.threshold = PlaybackThreshold.Everything

        self._loop_sound: T.Optional[Sound] = None
        self._loop_player = QMediaPlayer(self)
        self._loop_volume_adjustment: Number = 0
        self._loop_player.setAudioRole(QAudio.GameRole)
        self._loop_playlist = QMediaPlaylist(self)
        self._loop_playlist.setPlaybackMode(QMediaPlaylist.CurrentItemOnce)
        self._loop_player.setPlaylist(self._loop_playlist)
        self._loop_player.stateChanged.connect(
            self._on_loop_player_state_changed)

        self._one_shot_player = QMediaPlayer(self)
        self._one_shot_volume_adjustment: Number = 0
        self._one_shot_player.setAudioRole(QAudio.GameRole)
        self._one_shot_player.stateChanged.connect(
            self._on_one_shot_player_state_changed)

    @property
    def is_playing(self):
        return (self._loop_player.state() == QMediaPlayer.PlayingState
                or self._one_shot_player.state() == QMediaPlayer.PlayingState)

    def _on_loop_player_state_changed(self, state: QMediaPlayer.State) -> None:
        logger.trace("Loop player state changed: {!r}", state)
        if state != QMediaPlayer.StoppedState:
            return

        decibel = -self._loop_volume_adjustment
        logger.trace("Readjusting loop player volume by {}db", decibel)
        self.adjust_player_volume_by_decibel(self._loop_player, decibel)
        self._loop_volume_adjustment = 0

        # Loop playlist is empty
        if not self._loop_playlist.mediaCount():
            logger.trace("Loop playlist is empty, not queueing a new file")
            return

        # This shouldn't ever happen, it's just here to make mypy happy
        if not self._loop_sound:
            return

        file = random.choices(self._loop_sound.files,
                              [file.weight
                               for file in self._loop_sound.files])[0]
        index = self._loop_sound.files.index(file)
        logger.trace(
            "Loop player playing file: {!r} at playlist index: {}",
            file,
            index,
        )
        self._loop_playlist.setCurrentIndex(index)
        self._loop_player.play()

    def _on_one_shot_player_state_changed(self,
                                          state: QMediaPlayer.State) -> None:
        logger.trace("One-shot player state changed: {!r}", state)
        if state != QMediaPlayer.StoppedState:
            return

        decibel = -self._one_shot_volume_adjustment
        logger.trace("Readjusting one-shot player volume by {}db", decibel)
        self.adjust_player_volume_by_decibel(self._one_shot_player, decibel)
        self._one_shot_volume_adjustment = 0

        logger.trace("One-shot player stopped, resuming loop player")
        self._loop_player.play()

    def play_sound(self, sound: Sound) -> None:
        if sound.playback_threshold > self.threshold:
            logger.trace("Ignoring sound {!r} because of threshold", sound)
            return

        if sound.loop is Loop.Start:
            self._loop_sound = sound
            # New looping sound, rebuild playlist
            self._loop_playlist.clear()
            for file in sound.files:
                media = QUrl.fromLocalFile(file.file_name)
                self._loop_playlist.addMedia(media)

            # Select file based on weight and set the matching playlist index
            weights = [file.weight for file in sound.files]
            file = random.choices(sound.files, weights)[0]
            index = sound.files.index(file)
            self._loop_playlist.setCurrentIndex(index)

            logger.trace("Adjusting loop player volume by {}db",
                         file.volume_adjustment)
            self._loop_volume_adjustment = self.adjust_player_volume_by_decibel(
                self._loop_player, file.volume_adjustment)
            logger.trace("Adjusted One-shot player volume by {}db",
                         self._loop_volume_adjustment)
            self._loop_player.play()
            logger.trace(
                "Loop player playing file: {!r} at playlist index: {}",
                file,
                index,
            )
            return
        if sound.loop is Loop.Stop:
            logger.trace("Stopping loop player")
            self._loop_sound = None
            self._loop_playlist.clear()
            self._loop_player.stop()
        else:
            logger.trace("Pausing loop player for one-shot sound")
            self._loop_player.pause()

        file = random.choices(sound.files,
                              [file.weight for file in sound.files])[0]
        media = QUrl.fromLocalFile(file.file_name)
        self._one_shot_player.setMedia(media)
        self._one_shot_volume_adjustment = self.adjust_player_volume_by_decibel(
            self._one_shot_player, file.volume_adjustment)
        logger.trace("Adjusted one-shot player volume by {}db",
                     self._one_shot_volume_adjustment)
        self._one_shot_player.play()
        logger.trace("One-shot player playing file: {!r}", file)

    def set_player_volumes(self, volume: Number) -> None:
        volume = round(volume)
        self._loop_player.setVolume(volume)
        self._one_shot_player.setVolume(volume)

    # noinspection PyMethodMayBeStatic
    def adjust_player_volume_by_decibel(self, player: QMediaPlayer,
                                        decibel: Number) -> Number:
        original_volume = player.volume()
        target_volume = round(
            add_decibel_to_linear_volume(original_volume, decibel))
        player.setVolume(target_volume)

        # Return clamped volume difference, so increasing linear volume 100 by n > 1 db
        # returns 0
        return player.volume() - original_volume

    def set_threshold(self, threshold: PlaybackThreshold) -> None:
        logger.trace("Setting channel threshold: {!r}", threshold)
        self.threshold = threshold

        if not self._loop_sound:
            return

        if self._loop_sound.playback_threshold > threshold:
            logger.trace("Stopping loop player, new threshold too low")
            self._loop_playlist.clear()
            self._loop_player.stop()
            return

        logger.trace("Loop player state: {!r}", self._loop_player.state())
        if (self._loop_sound.playback_threshold <= threshold
                and self._loop_player.state() == QMediaPlayer.StoppedState):
            logger.trace(
                "Replaying sound: {!r} in loop player from stopped state")
            self.play_sound(self._loop_sound)
Beispiel #28
0
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()
Beispiel #29
0
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
Beispiel #30
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.videoWidget = QVideoWidget()
        self.mediaPlayer = QMediaPlayer()
        self.mediaPlaylist = QMediaPlaylist()
        # Add the video file path
        self.mediaPlaylist.addMedia(QUrl.fromLocalFile(os.path.abspath("./sample_data/sampleVideo.mp4")))
        # Set the video to played in a loop once it ends.
        self.mediaPlaylist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        # Set the QMediaPlaylist for the QMediaPlayer.
        self.mediaPlayer.setPlaylist(self.mediaPlaylist)
        # Add the QVideoWidget in the GridLayout.
        self.playerLayout.addWidget(self.videoWidget)
        # Set the video output from the QMediaPlayer to the QVideoWidget.
        self.mediaPlayer.setVideoOutput(self.videoWidget)
        # Set the QPushButtons to play, pause and stop the video in the QVideoWidget.
        self.playButton.clicked.connect(self.play_video)
        self.pauseButton.clicked.connect(self.pause_video)
        self.stopButton.clicked.connect(self.stop_video)
        # Set the total range for the QSlider.
        self.mediaPlayer.durationChanged.connect(self.change_duration)
        # Set the current value for the QSlider.
        self.mediaPlayer.positionChanged.connect(self.change_position)
        # Set the video position in QMediaPlayer based on the QSlider position.
        self.horizontalSlider.sliderMoved.connect(self.video_position)

    def play_video(self):
        """
        Handles the clicked signal generated by playButton and plays the video in the mediaPlayer.
        """
        self.mediaPlayer.play()

    def pause_video(self):
        """
        Handles the clicked signal generated by playButton and pauses video in the mediaPlayer.
        """
        self.mediaPlayer.pause()

    def stop_video(self):
        """
        Handles the clicked signal generated by playButton and stops the video in the mediaPlayer.
        """
        self.mediaPlayer.stop()

    def change_position(self, position):
        """
        Handles the positionChanged signal generated by the mediaPlayer.
        Sets the current value of the QSlider to the current position of the video in the QMediaPlayer.
        :param position: current position of the video in the QMediaPlayer.
        """
        self.horizontalSlider.setValue(position)

    def change_duration(self, duration):
        """
        Handles the durationChanged signal generated by the mediaPlayer.
        Sets the range of the QSlider.
        :param duration: Total duration of the video in the QMediaPlayer.
        """
        self.horizontalSlider.setRange(0, duration)

    def video_position(self, position):
        """
        Handles the sliderMoved signal generated by the horizontalSlider.
        Changes the position of the video in the QMediaPlayer on changing the value of the QSlider.
        :param position: Current position value of the QSlider.
        :return:
        """
        self.mediaPlayer.setPosition(position)
Beispiel #31
0
class VideoWindow(QWidget):
    def __init__(self, path=0, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Python Video Player Widget Example") 
        self.parent = parent
        self.path = path
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)

        self.videoWidget = QVideoWidget(self.parent)

        self.playButton = QPushButton()
        self.playButton.setEnabled(False)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play)

        self.positionSlider = QSlider(Qt.Horizontal)
        self.positionSlider.setRange(0, 0)
        self.positionSlider.sliderMoved.connect(self.setPosition)

        self.errorLabel = QLabel()
        self.errorLabel.setSizePolicy(QSizePolicy.Preferred,
                QSizePolicy.Maximum)

        # # Create new action
        # openAction = QAction(QIcon('open.png'), '&Open', self)        
        # openAction.setShortcut('Ctrl+O')
        # openAction.setStatusTip('Open movie')
        # openAction.triggered.connect(self.openFile)

        # # Create exit action
        # exitAction = QAction(QIcon('exit.png'), '&Exit', self)        
        # exitAction.setShortcut('Ctrl+Q')
        # exitAction.setStatusTip('Exit application')
        # exitAction.triggered.connect(self.exitCall)

        # # Create menu bar and add action
        # menuBar = self.menuBar()
        # fileMenu = menuBar.addMenu('&File')
        # #fileMenu.addAction(newAction)
        # fileMenu.addAction(openAction)
        # fileMenu.addAction(exitAction)

        # # Create a widget for window contents
        # wid = QWidget(self)
        # self.setCentralWidget(wid)

        # Create layouts to place inside widget
        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(self.playButton)
        controlLayout.addWidget(self.positionSlider)

        layout = QVBoxLayout()
        layout.addWidget(self.videoWidget)
        layout.addLayout(controlLayout)
        layout.addWidget(self.errorLabel)

        # Set widget to contain window contents
        self.setLayout(layout)

        self.mediaPlayer.setVideoOutput(self.videoWidget)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged) 

        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.error.connect(self.handleError)

        if path:
            self.openFile(path)
            self.play()
            self.play()


    def closeEvent(self, event):
        #self.videoWidget.stop()
        self.mediaPlayer.stop()
        del self.mediaPlayer
        self.videoWidget.close()

    def keyPressEvent(self, key):
        print(key)
        self.parent.keyPressEvent(key)

    def openFile(self, path):
        print(path)
        fileName = path
        #QFileDialog.getOpenFileName(self, "Open Movie",
        #QDir.homePath())

        if fileName != '':
            self.mediaPlayer.setMedia(
                    QMediaContent(QUrl.fromLocalFile(fileName)))
            self.playButton.setEnabled(True)

    def exitCall(self):
        sys.exit(app.exec_())

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(
                    self.style().standardIcon(QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(
                    self.style().standardIcon(QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)

    def handleError(self):
        self.playButton.setEnabled(False)
        self.errorLabel.setText("Error: " + self.mediaPlayer.errorString())