не работает слайдер громкости и как подключить плейлист к просмотру списка - PullRequest
0 голосов
/ 12 марта 2020
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import Qt
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent, QMediaMetaData
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog, QSlider
import glob
import os

list1=[]
song_list=[]


class Ui_MainWinpage(object):
    def setupUi(self, MainWinpage):
        MainWinpage.setObjectName("MainWinpage")
        MainWinpage.resize(507, 301)
        self.centralwidget = QtWidgets.QWidget(MainWinpage)
        self.centralwidget.setAutoFillBackground(True)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")

        # slider
        self.horizontalSlider = QtWidgets.QSlider(self.centralwidget)
        self.horizontalSlider.setGeometry(QtCore.QRect(190, 180, 160, 16))
        self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalSlider.setObjectName("horizontalSlider")
        self.horizontalSlider.valueChanged[int].connect(self.changeValue)
        self.horizontalSlider.setStyleSheet("background-color:royalblue;\n"
                                            "color: white;\n"
                                            "border-style: outset;\n"
                                            "border-width:2px;\n"
                                            "border-radius:10px;\n"
                                            "border-color:darkred;\n"
                                            "font:bold 14px;\n"
                                            "padding :6px;\n"
                                            "min-width:10px;\n"
                                            "\n"
                                            "\n"
                                            "")
        self.gridLayout.addWidget(self.horizontalSlider, 0, 0, 1, 3)

        self.play_song = QtWidgets.QPushButton(self.centralwidget)
        self.play_song.setObjectName("play_song")
        self.play_song.setStyleSheet("background-color:red;\n"
                                     "color: white;\n"
                                     "border-style: outset;\n"
                                     "border-width:2px;\n"
                                     "border-radius:10px;\n"
                                     "border-color:black;\n"
                                     "font:bold 14px;\n"
                                     "padding :6px;\n"
                                     "min-width:10px;\n"
                                     "\n"
                                     "\n"
                                     "")
        self.gridLayout.addWidget(self.play_song, 1, 0, 1, 1)

        self.pause_song = QtWidgets.QPushButton(self.centralwidget)
        self.pause_song.setObjectName("pause_song")
        self.pause_song.setStyleSheet("background-color:red;\n"
                                      "color: white;\n"
                                      "border-style: outset;\n"
                                      "border-width:2px;\n"
                                      "border-radius:10px;\n"
                                      "border-color:black;\n"
                                      "font:bold 14px;\n"
                                      "padding :6px;\n"
                                      "min-width:10px;\n"
                                      "\n"
                                      "\n"
                                      "")
        self.gridLayout.addWidget(self.pause_song, 1, 1, 1, 1)

        self.stop_song = QtWidgets.QPushButton(self.centralwidget)
        self.stop_song.setObjectName("stop_song")
        self.stop_song.setStyleSheet("background-color:red;\n"
                                     "color: white;\n"
                                     "border-style: outset;\n"
                                     "border-width:2px;\n"
                                     "border-radius:10px;\n"
                                     "border-color:black;\n"
                                     "font:bold 14px;\n"
                                     "padding :6px;\n"
                                     "min-width:10px;\n"
                                     "\n"
                                     "\n"
                                     "")
        self.gridLayout.addWidget(self.stop_song, 1, 2, 1, 1)

        self.previous = QtWidgets.QPushButton(self.centralwidget)
        self.previous.setObjectName("previous")
        self.previous.setStyleSheet("background-color:red;\n"
                                    "color: white;\n"
                                    "border-style: outset;\n"
                                    "border-width:2px;\n"
                                    "border-radius:10px;\n"
                                    "border-color:black;\n"
                                    "font:bold 14px;\n"
                                    "padding :6px;\n"
                                    "min-width:10px;\n"
                                    "\n"
                                    "\n"
                                    "")
        self.gridLayout.addWidget(self.previous, 2, 0, 1, 1)

        self.shuffle = QtWidgets.QPushButton(self.centralwidget)
        self.shuffle.setObjectName("shuffle")
        self.shuffle.setStyleSheet("background-color:red;\n"
                                   "color: white;\n"
                                   "border-style: outset;\n"
                                   "border-width:2px;\n"
                                   "border-radius:10px;\n"
                                   "border-color:black;\n"
                                   "font:bold 14px;\n"
                                   "padding :6px;\n"
                                   "min-width:10px;\n"
                                   "\n"
                                   "\n"
                                   "")
        self.gridLayout.addWidget(self.shuffle, 2, 1, 1, 1)

        self.next = QtWidgets.QPushButton(self.centralwidget)
        self.next.setObjectName("next")
        self.next.setStyleSheet("background-color:red;\n"
                                "color: white;\n"
                                "border-style: outset;\n"
                                "border-width:2px;\n"
                                "border-radius:10px;\n"
                                "border-color:black;\n"
                                "font:bold 14px;\n"
                                "padding :6px;\n"
                                "min-width:10px;\n"
                                "\n"
                                "\n"
                                "")
        self.gridLayout.addWidget(self.next, 2, 2, 1, 1)
        # for volume
        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setMaximum(32767)
        self.volumeSlider.setPageStep(1024)
        self.gridLayout.addWidget(self.volumeSlider, 4, 0, 1, 1)

        # for listing in Sangeet mainwinpage
        self.gridLayout.setObjectName("gridLayout")
        self.listView = QtWidgets.QListView(MainWinpage)
        self.listView.setObjectName("listView")

        songs_mp3s = ['num1', 'num2', 'num3']
        model = QtGui.QStandardItemModel()
        self.listView.setModel(model)

        for i in songs_mp3s:
            item = QtGui.QStandardItem(i)
            model.appendRow(item)
        self.gridLayout.addWidget(self.listView, 5, 1, 1, 1)

        MainWinpage.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWinpage)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 507, 22))
        self.menubar.setObjectName("menubar")
        self.menufile = QtWidgets.QMenu(self.menubar)
        self.menufile.setObjectName("menufile")
        MainWinpage.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWinpage)
        self.statusbar.setObjectName("statusbar")
        MainWinpage.setStatusBar(self.statusbar)
        self.actionopen = QtWidgets.QAction(MainWinpage)
        self.actionopen.setObjectName("actionopen")
        self.menufile.addAction(self.actionopen)
        self.menubar.addAction(self.menufile.menuAction())

        self.pushButton = QtWidgets.QPushButton(MainWinpage)

        self.pushButton.setObjectName("pushButton")
        # for Qtmultimedia
        self.media_player = QMediaPlayer()
        self.media_player.durationChanged.connect(self.horizontalSlider.setMaximum)
        self.media_player.positionChanged.connect(self.horizontalSlider.setValue)
        self.volumeSlider.valueChanged.connect(self.changeVolume)
        self.retranslateUi(MainWinpage)
        QtCore.QMetaObject.connectSlotsByName(MainWinpage)

    def retranslateUi(self, MainWinpage):
        _translate = QtCore.QCoreApplication.translate
        MainWinpage.setWindowTitle(_translate("MainWinpage", "Sangeet"))
        self.play_song.setText(_translate("MainWinpage", "play"))
        self.pause_song.setText(_translate("MainWinpage", "pause"))
        self.stop_song.setText(_translate("MainWinpage", "stop"))
        self.previous.setText(_translate("MainWinpage", "previous"))
        self.shuffle.setText(_translate("MainWinpage", "playlist"))
        self.next.setText(_translate("MainWinpage", "next"))
        self.menufile.setTitle(_translate("MainWinpage", "file"))
        self.actionopen.setText(_translate("MainWinpage", "open "))

        self.previous.setText(_translate("MainWinpage", "Browse"))
        self.previous.clicked.connect(self.pushButton_handler)
        self.play_song.clicked.connect(self.play_music)
        self.pause_song.clicked.connect(self.pause_music)
        self.stop_song.clicked.connect(self.stop_music)
        self.shuffle.clicked.connect(self.playlist_handler)

    def changeValue(self, value):
        blocked = self.media_player.blockSignals(True)
        value = self.horizontalSlider.value()
        self.media_player.setPosition(value)
        self.media_player.blockSignals(blocked)

    def changeVolume(self, value):
        self.volumeSlider.volume = value
        self.volumeSlider.setVolume.durationChanged.connect(self.horizontalSlider.setMaximum)
        self.volumeSlider.value.positionChanged.connect(self.horizontalSlider.setValue)
        print("volume is:", value)

    def filebrowser(self, ext=""):
        return [f for f in glob.glob(f"*{ext}")]

    def calc(self):
        self.filebrowser()
        x = self.filebrowser(".mp3")
        y = len(x)
        print("number of items in list-", y)
        for w in x:
            song_list.append(w)
            print(w)

    def pushButton_handler(self):
        print("Button pressed")
        self.open_dialog_box()

    def playlist_handler(self):
        print("Button pressed")
        self.open_dialog_box_for_playlist()

        # for opening that file which you want to open

    def open_dialog_box(self):
        filename = QFileDialog.getOpenFileName()
        path = str(filename[0])
        self.media_player.setMedia(QMediaContent(QtCore.QUrl.fromLocalFile(path)))
        print("path is ", path)
        self.globalpath = path
        print("global paths is ", self.globalpath)

    def open_dialog_box_for_playlist(self):
        filename = QFileDialog.getExistingDirectory()
        path = str(filename)
        # self.media_player.setMedia(QMediaContent(QtCore.QUrl.fromLocalFile(path)))
        # print("path is ",path)
        # self.global_playlist_path = path
        # print("global paths is ", self.global_playlist_path)
        self.getFolderPlaylist(path)
        # self.calc()

        # path = '/home/darshan/Sangeet/pyqtlayout'
        # for list of songs in folder

    def getFolderPlaylist(self, paths):
        ls = os.listdir(paths)
        list_songs_mp3s=[]
        for item in ls:
            if item.count('mp3'):
                list_songs_mp3s.append(item)

        if len(list_songs_mp3s) > 0:
            folderName = os.path.basename(paths)
            print("mp3s are--", list_songs_mp3s)
            return folderName, paths, list_songs_mp3s
        else:
            return None

        # for playing that file which we had choosen from

    def play_music(self):
        artist = self.media_player.metaData(QMediaMetaData.AlbumArtist)
        title = self.media_player.metaData(QMediaMetaData.Title)
        self.media_player.play()
        print("song name:", self.globalpath)
        print(f"Now playing: {title} by {artist}")

        # for pause that selected music

    def pause_music(self):
        self.media_player.pause()
        print("song is paused")

        # for stoping that music

    def stop_music(self):
        self.media_player.stop()
        print("song is stopped")


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWinpage = QtWidgets.QMainWindow()
    ui = Ui_MainWinpage()
    ui.setupUi(MainWinpage)
    MainWinpage.show()
    sys.exit(app.exec_())

1 Ответ

0 голосов
/ 12 марта 2020

Следующие строки не имеют никакого смысла:

self.volumeSlider.setVolume.durationChanged.connect(self.horizontalSlider.setMaximum)
self.volumeSlider.value.positionChanged.connect(self.horizontalSlider.setValue)

Вы бы обнаружили это самостоятельно, если бы попытались запустить его в командной оболочке / командной строке (но ваша IDE должна была предупредить вас о в любом случае).

Как уже указывалось в комментарии к вашему предыдущему вопросу, QSlider имеет атрибут no setVolume, а value является свойством , которое должен вызываться (self.volumeSlider.value()), он возвращает текущее значение ползунка в виде целого числа, а целые числа не имеют атрибута positionChanged.

Измените функцию следующим образом:

def changeVolume(self, value):
    self.media_player.setVolume(value / self.volumeSlider.maximum() * 100)

Формула: вычислить отношение текущего значения на основе полного экстента ползунка (value / maximum), а затем умножить его на 100, поскольку QMediaPlayer принимает значения в процентах.

Внимательно изучите документацию о QSlider и его базовый класс QAbstractSlider .

Наконец, никогда не используйте файлы python, сгенерированные pyuic, для создания своих программ. НИКОГДА .
Они должны использоваться как импортированные модули, и ваша программа должна быть создана в отдельном файле. Прочитайте документацию о , используя Designer , чтобы узнать больше.

...