Beispiel #1
0
class VideoPlayer(QVideoWidget):
    def __init__(self):
        super(VideoPlayer, self).__init__()

        self._player = QMediaPlayer()
        self._playlist = QMediaPlaylist()
        self._stopped = True

    # プレイリストに動画を追加
    def addMedia(self, media_file):
        media_content = QMediaContent(QUrl.fromLocalFile(media_file))
        self._playlist.addMedia(media_content)

    # クリックでポーズ・再生の切り替え
    def mousePressEvent(self, event):
        if self._stopped:
            self.play()
        else:
            self._player.pause()
            self._stopped = True

    # ダブルクリックで動画を読み込み,再生
    def mouseDoubleClickEvent(self, event):
        self._player.setVideoOutput(self)
        self._player.setPlaylist(self._playlist)
        self.play()

    def play(self):
        self._player.play()
        self._stopped = False
Beispiel #2
0
class VideoPlayer(QVideoWidget):
    def __init__(self):
        super(VideoPlayer, self).__init__()

        self._player = QMediaPlayer()
        self._playlist = QMediaPlaylist()
        self._stopped = True

    # プレイリストに動画を追加
    def addMedia(self, media_file):
        media_content = QMediaContent(QUrl.fromLocalFile(media_file))
        self._playlist.addMedia(media_content)

    # クリックでポーズ・再生の切り替え
    def mousePressEvent(self, event):
        if self._stopped:
            self.play()
        else:
            self._player.pause()
            self._stopped = True

    # ダブルクリックで動画を読み込み,再生
    def mouseDoubleClickEvent(self, event):
        self._player.setVideoOutput(self)
        self._player.setPlaylist(self._playlist)
        self.play()

    def play(self):
        self._player.play()
        self._stopped = False
class VideoPlayer(QMainWindow):

    def __init__(self):
        super(VideoPlayer, self).__init__()
        self._screen_size = QApplication.primaryScreen().size()
        sw, sh = self._screen_size.width(), self._screen_size.height()
        self.resize(sw, sh)
        self.setStyleSheet('background: black')
        # # PLAYER
        self._playList = QMediaPlaylist()
        self._playWidget = QVideoWidget(self)
        self._playWidget.resize(sw, sh)
        self._player = QMediaPlayer(self)
        self._player.setPlaylist(self._playList)
        self._player.setVideoOutput(self._playWidget)
        self._playList.addMedia(QMediaContent(
            QUrl.fromLocalFile('/Users/huangkai/Documents/PycharmProjects/AllTest/Qt插入背景/AddVideos/Videos/yellow.mov')))
        self._playList.setPlaybackMode(QMediaPlaylist.Loop)
        self._player.play()

    def keyPressEvent(self, a0: QKeyEvent) -> None:
        key = a0.key()
        if key == Qt.Key_Escape:
            self.resize(100, 100)
            self._playWidget.resize(100, 100)
            self._player.stop()
        elif key in (Qt.Key_Return, Qt.Key_Enter):
            self.resize(self._screen_size.width(), self._screen_size.height())
Beispiel #4
0
class SoundPack:
    def __init__(self, name, bg, shoot, hit, score_up, swap, loose, win):
        """
        Creates Soundpack

        name - soundpack name
        other params - non-absolute way to files
        """
        self.name = name

        self.back = QMediaPlaylist()
        for sound in bg:
            url = QUrl.fromLocalFile(os.path.join(os.getcwd(), sound))
            self.back.addMedia(QMediaContent(url))
        self.back.setPlaybackMode(QMediaPlaylist.Loop)
        self.bg = QMediaPlayer()
        self.bg.setPlaylist(self.back)
        self.bg.setVolume(30)

        self.shoot = QSound(shoot)
        self.hit = QSound(hit)
        self.score_up = QSound(score_up)
        self.swap = QSound(swap)
        self.loose = QSound(loose)
        self.win = QSound(win)
Beispiel #5
0
class MusicList(QListWidget):
    def __init__(self):
        super(MusicList, self).__init__()
        self.__musicList = []
        self.setFixedWidth(250)
        self.setFont(QFont('宋体', 10,))
        self.setObjectName('musicList')
        self.setStyleSheet('#musicList{background-color: rgba(0, 0, 0, 120); color: "green";} #musicList:item{height: 25;}')
        self.itemDoubleClicked.connect(self.music_double_clicked)

        # 初始化多媒体播放器和播放列表
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist(self.player)
        self.player.setPlaylist(self.playlist)

    def add_music_item(self, file_names):
        for file in file_names:
            self.addItem(file.split('/')[-1])
            self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(file)))

    def music_double_clicked(self):
        music_list_index = self.currentRow()
        self.music_play(music_list_index)

    def music_play(self, music_list_index):
        self.playlist.setCurrentIndex(music_list_index)
        self.player.play()

    def add_network_music(self, music_name, music_url):
        print(music_name)
        self.addItem(music_name)
        self.playlist.addMedia(QMediaContent(QUrl(music_url)))
Beispiel #6
0
class SoundPlayerWorker(QObject):
    def __init__(self, args=(), kwargs=None):
        super().__init__()
        self.media_player = QMediaPlayer(flags=QMediaPlayer.LowLatency)
        self.playlist = QMediaPlaylist()
        self.media_player.setPlaylist(self.playlist)
        self._priority = 0

    def play_sound(self, file="", priority=0, override=False):
        """
        Method to add a new sound to play
        :param file: str
        :param override:
        :return:
        """

        # logging.info(f"file: {file}, priority: {priority}, self._priority: {self._priority}")

        if priority > self._priority:
            self.media_player.stop()
            self.playlist.clear()
            self._priority = priority

        # if override:
        #     self.media_player.stop()
        #     self.playlist.clear()

        # logging.info(f"request to play: {file}, override set to: {override}, mediaCount: {self.playlist.mediaCount()}")

        self.playlist.addMedia(QMediaContent(QUrl(file)))

        # logging.info(f"request to play, after adding file: {file}, override set to: {override}, mediaCount: {self.playlist.mediaCount()}")

        if self.media_player.state() == 0:
            self.media_player.play()

    def state_changed(self):
        """
        Method called when the media_player state is changed
        :return: 
        """
        if self.media_player.state() == 0:
            self._priority = 0

    def check_playlist_index(self):
        """
        Method to check to see if we've reached the end of the playlist or not
        :return:
        """
        if self.playlist.currentIndex() == -1:
            self.playlist.clear()

    def stop(self):
        """
        Method to stop the sound from playing any further
        :return:
        """
        self.media_player.stop()
Beispiel #7
0
class PlayVideo(DisplayEvent):
    def __init__(self, frame, settings):
        super().__init__(frame, settings)

        self.url = QUrl(settings.get("url"))
        self.start_time = settings.get("start", 0) * 1000
        self.duration = settings.get("duration")
        self.loop = settings.get("loop", True)
        self.volume = settings.get("volume", 100)
        self.playback_rate = settings.get("playbackRate", 1.0)

    def do_tick(self):
        if self.player:
            self.logging.info("position: %s/%s status: %s error: %s" % (
                self.player.position(),
                self.player.duration(),
                self.player.mediaStatus(),
                self.player.errorString(),
            ))
            if self.player.errorString():
                self.logging.error(self.player.errorString())
                self.cancel()

    def do_initialize(self):
        super().do_initialize()
        self.video = QVideoWidget(self.widget)
        self.add_widget(self.video)
        self.video.show()

        self.media = QMediaContent(self.url)
        self.playlist = QMediaPlaylist(self.video)
        self.playlist.addMedia(self.media)
        self.playlist.setPlaybackMode(
            QMediaPlaylist.Loop if self.loop else QMediaPlaylist.Sequential)

        self.player = QMediaPlayer(self.widget)
        self.player.setVideoOutput(self.video)
        self.player.setVolume(self.volume)
        self.player.setPlaybackRate(self.playback_rate)

    def do_run(self):
        super().do_run()
        self.player.setPlaylist(self.playlist)
        self.player.setPosition(self.start_time)
        self.player.play()

        if self.player.errorString():
            self.logging.error(self.player.errorString())
            self.cancel()

    def do_stop(self):
        super().do_stop()
        self.player.stop()

    def do_reset(self):
        self.player = None
        self.video = None
Beispiel #8
0
        def play_music():
            playlist = QMediaPlaylist(self)
            url = QUrl.fromLocalFile(
                resource_path("Wham! - Last Christmas.mp3"))
            playlist.addMedia(QMediaContent(url))
            playlist.setPlaybackMode(QMediaPlaylist.Loop)

            player = QMediaPlayer(self)
            player.setPlaylist(playlist)
            player.play()
class WelcomeWindow(QMainWindow, Ui_WelcomeWindow):
    def __init__(self, welcomeVid):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.pList = QMediaPlaylist()
        media = QUrl("file://" + welcomeVid)
        self.pList.addMedia(QMediaContent(media))
        self.player.setPlaylist(self.pList)
        self.pList.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        self.player.setVideoOutput(self.welcomeVideo)
Beispiel #10
0
class VideoPlayer(QWidget):
    # noinspection PyArgumentList
    def __init__(self, width: int, height: int, parent=None):
        super(VideoPlayer, self).__init__(parent)
        video_item = QGraphicsVideoItem()
        video_item.setAspectRatioMode(Qt.IgnoreAspectRatio)
        video_item.setSize(QSizeF(width, height))
        scene = QGraphicsScene(self)
        scene.addItem(video_item)
        graphics_view = QGraphicsView(scene)
        graphics_view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        graphics_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        layout = QVBoxLayout()
        layout.addWidget(graphics_view)
        self.setLayout(layout)
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.mediaPlayer.setVideoOutput(video_item)
        self.mediaPlayer.setVolume(0)

    def play(self):
        self.mediaPlayer.play()

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

    # noinspection PyArgumentList
    def load_loop(self, name):
        global config
        play_loop = QMediaPlaylist()
        play_loop.addMedia(QMediaContent(QUrl.fromLocalFile(config['preview_path'] + name)))
        play_loop.setPlaybackMode(QMediaPlaylist.Loop)
        self.mediaPlayer.setPlaylist(play_loop)

    # noinspection PyArgumentList
    def load(self, name):
        global config
        self.mediaPlayer.stop()
        if os.path.isfile(config['preview_path'] + name):
            local = QUrl.fromLocalFile(config['preview_path'] + name)
        else:
            local = QUrl.fromLocalFile(config['preview_path'] + 'default.mp4')
        media = QMediaContent(local)
        self.mediaPlayer.setMedia(media)
Beispiel #11
0
class musicPlayer(QObject):
    def __init__(self):
        super().__init__()
        self.playlist = QMediaPlaylist()
        self.url = QUrl.fromLocalFile('Music/1.mp3')
        self.playlist.addMedia(QMediaContent(self.url))
        self.url = QUrl.fromLocalFile('Music/2.mp3')
        self.playlist.addMedia(QMediaContent(self.url))
        self.url = QUrl.fromLocalFile('Music/3.mp3')
        self.playlist.addMedia(QMediaContent(self.url))
        self.url = QUrl.fromLocalFile('Music/4.mp3')
        self.playlist.addMedia(QMediaContent(self.url))
        self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
        print("stigao do 1")
        self.player = QMediaPlayer()
        self.player.setPlaylist(self.playlist)
        self.player.play()
        print("stigao do 2")
        #self.player.setMuted(True)
Beispiel #12
0
class WaitWidget(QVideoWidget, Ui_WaitWidget):

    pressedSignal = pyqtSignal()

    def __init__(self, waitVid):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.pList = QMediaPlaylist()
        media = QUrl("file://" + waitVid)
        self.pList.addMedia(QMediaContent(media))
        self.player.setPlaylist(self.pList)
        self.pList.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        self.player.setVideoOutput(self)
        self.setFullScreen(True)

    def mousePressEvent(self, event):
        self.pressedSignal.emit()

    def keyPressEvent(self, event):
        self.pressedSignal.emit()
Beispiel #13
0
class MusicList(QListWidget):
    def __init__(self):
        super(MusicList, self).__init__()
        self.__musicList = []
        self.setFixedWidth(250)
        self.setFont(QFont(
            '宋体',
            10,
        ))
        self.setObjectName('musicList')
        self.setStyleSheet(
            '#musicList{background-color: rgba(0, 0, 0, 120); color: "green";} #musicList:item{height: 25;}'
        )
        self.itemDoubleClicked.connect(self.music_double_clicked)

        # 初始化多媒体播放器和播放列表
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist(self.player)
        self.player.setPlaylist(self.playlist)

    def add_music_item(self, file_names):
        for file in file_names:
            self.addItem(file.split('/')[-1])
            self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(file)))

    def music_double_clicked(self):
        music_list_index = self.currentRow()
        self.music_play(music_list_index)

    def music_play(self, music_list_index):
        self.playlist.setCurrentIndex(music_list_index)
        self.player.play()

    def add_network_music(self, music_name, music_url):
        print(music_name)
        self.addItem(music_name)
        self.playlist.addMedia(QMediaContent(QUrl(music_url)))
Beispiel #14
0
class SoundPlayer:
    def __init__(self, parent):
        self.parent = parent

        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()

    def play(self, playlists, startRow=0, option=QMediaPlaylist.Sequential):
        if self.player.state() == QMediaPlayer.PausedState:
            self.player.play()
        else:
            self.createPlaylist(playlists, startRow, option)
            self.player.setPlaylist(self.playlist)
            self.playlist.setCurrentIndex(startRow)
            self.player.play()

    def pause(self):
        self.player.pause()

    def stop(self):
        self.player.stop()

    def createPlaylist(self,
                       playlists,
                       startRow=0,
                       option=QMediaPlaylist.Sequential):
        self.playlist.clear()

        for path in playlists:
            url = QUrl.fromLocalFile(path)
            self.playlist.addMedia(QMediaContent(url))

        self.playlist.setPlaybackMode(option)

    def upateVolume(self, vol):
        self.player.setVolume(vol)
Beispiel #15
0
def play(file_name: str):
    if not os.path.exists(file_name):
        raise FileNotFoundError(file_name)

    app = QCoreApplication([])

    url = QUrl.fromLocalFile(file_name)

    playlist = QMediaPlaylist()
    playlist.addMedia(QMediaContent(url))

    player = QMediaPlayer()
    player.setPlaylist(playlist)
    player.play()

    def tick():
        if player.state() == QMediaPlayer.StoppedState:
            app.quit()

    timer = QTimer()
    timer.timeout.connect(tick)
    timer.start(1000)

    app.exec()
class AudioPlayer(QObject):

    songPositionChanged = pyqtSignal(int)
    songDurationChanged = pyqtSignal(int)
    stateChanged = pyqtSignal(int)
    playlistChanged = pyqtSignal(QMediaPlaylist, int)

    currentSongChanged = pyqtSignal(str, str, bytes)
    currentSelectionChanged = pyqtSignal(UUID, int)

    customPlaylistCreated = pyqtSignal(UUID, str)
    libraryPlaylistCreated = pyqtSignal(UUID)

    addedToLibraryPlaylist = pyqtSignal(UUID, list)
    addedToCustomPlaylist = pyqtSignal(UUID, list)

    updatedLibraryPlaylist = pyqtSignal(UUID, list)

    playlistRemoved = pyqtSignal(UUID)

    def __init__(self, volumeLevel=40, playbackMode=QMediaPlaylist.Sequential,
                 parent=None):
        super(AudioPlayer, self).__init__(parent)

        self.__player = QMediaPlayer()
        self.__player.setVolume(volumeLevel)

        self.__player.currentMediaChanged.connect(self._onMediaChanged)
        self.__player.stateChanged.connect(
            lambda state: self.stateChanged.emit(int(state)))
        self.__player.positionChanged.connect(
            lambda x: self.songPositionChanged.emit(x))
        self.__player.durationChanged.connect(
            lambda x: self.songDurationChanged.emit(x))

        self.__playlistManager = PlaylistManger()

        self.__playlistManager.customPlaylistCreated.connect(
            lambda uuid, name: self.customPlaylistCreated.emit(uuid, name))
        self.__playlistManager.libraryPlaylistCreated.connect(
            lambda p: self.libraryPlaylistCreated.emit(p))
        
        self.__playlistManager.currentPlaylistChanged.connect(
            self._onChangedPlaylist)
        self.__playlistManager.currentPlaylistChanged.connect(
            lambda p, i: self.playlistChanged.emit(p, i))

        self.__playlistManager.playlistRemoved.connect(
            lambda uuid: self.playlistRemoved.emit(uuid))

        self.__playlistManager.addedToLibraryPlaylist.connect(
            lambda uuid, l: self.addedToLibraryPlaylist.emit(uuid, l))
        self.__playlistManager.addedToCustomPlaylist.connect(
            lambda uuid, l: self.addedToCustomPlaylist.emit(uuid, l))

        self.__playlistManager.updatedLibraryPlaylist.connect(
            lambda uuid, l: self.updatedLibraryPlaylist.emit(uuid, l))

    def createCustomPlaylist(self, name=None, urls=None):
        self.__playlistManager.createCustomPlaylist(name, urls)

    def createLibraryPlaylist(self, urls=None):
        self.__playlistManager.createLibraryPlaylist(urls)

    def addToLibraryPlaylist(self, url=None):
        self.__playlistManager.addToLibraryPlaylist(url)

    def updateLibraryPlaylist(self, url=None):
        self.__playlistManager.updateLibraryPlaylist(url)

    def renamePlaylist(self, uuid, newName):
        self.__playlistManager.renamePlaylist(uuid, newName)

    def addSongsToCustomPlaylist(self, uuid, urls=[]):
        self.__playlistManager.addSongsToCustomPlaylist(uuid, urls)

    def removeSong(self, uuid, row):
        self.__playlistManager.removeSong(uuid, row)

    def setPlaylist(self, uuid, index=0):
        if (self.__player.playlist() and
                self.__playlistManager.isCurrentPlaylist(uuid)):
            if index == self.__player.playlist().currentIndex():
                if self.__player.state() == QMediaPlayer.PlayingState:
                    self.__player.pause()
                else:
                    self.__player.play()
            else:
                self.__player.playlist().setCurrentIndex(index)
        else:
            self.__playlistManager.setPlaylist(uuid, index)

    def hasLibraryPlaylist(self):
        return self.__playlistManager.hasLibraryPlaylist()

    def removePlaylist(self, uuid):
        self.__playlistManager.removePlaylist(uuid)

    def getCurrentPlaylist(self):
        self.__playlistManager.getCurrentPlaylist()

    def getCurrentQMediaPlaylist(self):
        self.__player.playlist()

    def isPlayerAvailable(self):
        return self.__player.isAvailable()

    def getDuration(self):
        return self.__player.duration()

    def getPlayer(self):
        return self.__player

    def getState(self):
        return self.__player.state()

    def play(self):
        if self.__player.playlist():
            self.__player.play()

    def pause(self):
        if self.__player.playlist():
            self.__player.pause()

    def stop(self):
        if self.__player.playlist():
            self.__player.stop()

    def previousEnhanced(self, sameSongMillis):
        if self.__player.position() <= sameSongMillis:
            self.previous()
        else:
            self.__player.setPosition(0)

    def previous(self):
        if self.__player.playlist():
            self.__player.playlist().previous()

    def next(self):
        if self.__player.playlist():
            self.__player.playlist().next()

    def setVolume(self, value):
        self.__player.setVolume(value)

    def setPosition(self, milliseconds):
        self.__player.setPosition(milliseconds)

    def playlistCurrentIndex(self):
        if self.__player.playlist():
            return self.__player.playlist().currentIndex()

    def setCurrentPlaylistIndex(self, index):
        if self.__player.playlist():
            self.__player.playlist().setCurrentIndex(index)

    def _onChangedPlaylist(self, playlist, index, playIt=False):
        self.__player.setPlaylist(playlist)
        if playlist:
            playlist.setCurrentIndex(index)
        if playIt:
            self.play()

    def _onMediaChanged(self, media):
        if media.isNull() and self.__player.playlist():
            self.__player.playlist().setCurrentIndex(0)
            media = self.__player.playlist().media(0)
        if media.isNull():
            return

        title, artist, cover = self.__playlistManager.getBasicSongInfo(media)

        self.currentSongChanged.emit(title, artist, cover)

        uuid = self.__playlistManager.getCurrentPlaylistUuid()
        index = self.__playlistManager.getCurrentSongIndex()
        self.currentSelectionChanged.emit(uuid, index)

    # def saveSettings(self):
    #     # settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
    #     #                      QCoreApplication.organizationName(),
    #     #                      QCoreApplication.applicationName())

    #     # settings.beginGroup("music_player")

    #     # # if self.__playlistManager.getLibraryPlaylist():
    #     # #     libraryDirectories = self.__playlistManager.getLibraryPlaylist().getDirectories()
    #     # #     settings.beginWriteArray('library_playlist',
    #     # #                              len(libraryDirectories))
    #     # #     for index, value in enumerate(libraryDirectories):
    #     # #         settings.setArrayIndex(index)
    #     # #         settings.setValue("url", value)
    #     # #     settings.endArray()

    #     # customPlaylists = self.__playlistManager.getCustomPlaylists()
    #     # settings.beginWriteArray('custom_playlists',
    #     #                          len(customPlaylists))
    #     # for index, value in enumerate(customPlaylists):
    #     #     settings.setArrayIndex(index)
    #     #     playlistName = settings.value('name', value.getName())
    #     #     playlistUrls = value.getAddedSongUrls()
    #     #     settings.beginWriteArray(playlistName,
    #     #                              len(playlistUrls))
    #     #     for i, v in enumerate(playlistUrls):
    #     #         settings.setArrayIndex(i)
    #     #         settings.setValue("url", v)
    #     #     settings.endArray()
    #     # settings.endArray()

    #     # settings.endGroup()
    #     # if self.__playlistManager.getLibraryPlaylist():
    #     #     libraryDirectories = self.__playlistManager.getLibraryPlaylist().getDirectories()
    #     #     settings.beginWriteArray('library_playlist',
    #     #                              len(libraryDirectories))
    #     #     for index, value in enumerate(libraryDirectories):
    #     #         settings.setArrayIndex(index)
    #     #         settings.setValue("url", value)
    #     #     settings.endArray()

    #     customPlaylists = self.__playlistManager.getCustomPlaylists()
    #     for playlist in customPlaylists:
    #         playlistName = playlist.getName()
    #         for url in playlist:
    #             pass

    # def restoreSettings(self):
    #     settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
    #                          QCoreApplication.organizationName(),
    #                          QCoreApplication.applicationName())

    #     settings.beginGroup("music_player")

    #     # size = settings.beginReadArray('library_playlist')
    #     # libraryDirectories = []
    #     # for i in range(size):
    #     #     settings.setArrayIndex(i)
    #     #     libraryDirectories.append(settings.value("url"))
    #     # settings.endArray()

    #     customPlaylists = {}
    #     size = settings.beginReadArray('custom_playlists')
    #     for i in range(size):
    #         urls = []
    #         settings.setArrayIndex(i)
    #         playlistName = settings.value('name')
    #         print(playlistName)
    #         size2 = settings.beginReadArray(playlistName)
    #         for j in range(size2):
    #             settings.setArrayIndex(j)
    #             url = settings.value("url")
    #             urls.append(url)
    #         settings.endArray()
    #         customPlaylists[playlistName] = urls
    #     settings.endArray()

    #     settings.endGroup()

    #     print('-------')
    #     print(customPlaylists)





        # settings = QSettings(QCoreApplication.organizationName(),
        #                      QCoreApplication.applicationName())
        # settings.beginGroup("music_player")

        # size = settings.beginReadArray('library_playlist')
        # if not size == 0:
        #     for i in range(0, size):
        #         settings.setArrayIndex(i)
        #         url = settings.value("url")
        # settings.endArray()

        # if url:
        #     from audio.playlist_models import DirectoryPlaylist

        #     playlist = DirectoryPlaylist()
        #     playlist.add_directory(url)
        #     self.addAndSetPlaylist(playlist, 2)

        # settings.endGroup()
        pass
Beispiel #17
0
class Reproductor(Genesis, QMainWindow):

    """ Instalar MatroskaSplitter y LAVFilters(Codecs), para que pueda reproducir videos y audio

    LAVFilters
    https://github.com/Nevcairiel/LAVFilters/releases
    
    MatroskaSplitter
    https://haali.su/mkv/  
    """
    
    def __init__(self, *args, **kwargs):
        super(Reproductor, self).__init__()

        self.transcurso = 0
        
        # Centramos la ventana principal
        self.centrar()

        # Inicializamos el modulo QMediaPlayer
        self.media = QMediaPlayer()
        self.media.setVolume(5)
        self.reproducir.setEnabled(False)

        # Setup the playlist.
        self.lista_repro = QMediaPlaylist()
        self.media.setPlaylist(self.lista_repro)

        self.modelo = ListaModelo(self.lista_repro)
        self.lista.setModel(self.modelo)

        self.lista_repro.currentIndexChanged.connect(self.cambio_lista_repro)

        modelo_seleccion = self.lista.selectionModel()
        modelo_seleccion.selectionChanged.connect(self.seleccion_lista_repro)


# **********  Inicializamos el modulo QVideoWidget *******
        self.video = QVideoWidget()

        # Agregamos el modulo QVideoWidget al grid donde se mostrara el video
        self.reproductor.addWidget(self.video)

        # Tambien lo agregamos al modulo QMediaPlayer
        self.media.setVideoOutput(self.video)

        # Conectamos el boton de reproducir con su metodo correspondiente
        self.reproducir.clicked.connect(self.play_video)

        # Conectamos el Skider del tiempo con su metodo correspondiente
        self.tiempo.sliderMoved.connect(self.posicion_establecida)
    

# ******  Conectamos los estados del modulo QMediaPlayer con sus correspondientes metodos  *****
        self.media.stateChanged.connect(self.cambios_video)
        self.media.positionChanged.connect(self.posicion_video)
        self.media.durationChanged.connect(self.duracion_video)
        self.total_duracion = 0

        self.cargar.clicked.connect(self.abrir_archivo)
        #self.marco.origen.connect(self.arrastrar_soltar)

        self.parar.pressed.connect(self.media.stop)
        self.atras.pressed.connect(self.lista_repro.previous)
        self.adelante.pressed.connect(self.lista_repro.next)
        self.volumen.valueChanged.connect(self.media.setVolume)
        self.logo_volumen.clicked.connect(self.silenciar)
        self.lista.doubleClicked.connect(self.play_video)
        self.video.keyPressEvent = self.keyPressEvent

#         ****** Boton de menu ******
        self.lista.setMinimumSize(QSize(0, 0))
        self.lista_visible = True
        self.menu.clicked.connect(self.boton_menu)

        self.setAcceptDrops(True)

        self.primera_reproduccion = True
        self.show()

# ---------------- Inicio de Metodos --------------------------- #

    # Detectamos una tecla presionada
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_F11 or event.key() == Qt.Key_Escape and self.video.isFullScreen():
            self.fullscreen_change()
        elif event.key() == Qt.Key_Space:
            self.play_video()

    #Pantalla completa
    def fullscreen_change(self):
        if self.video.isFullScreen():
            self.video.setFullScreen(False)
            self.lista.setMinimumSize(QSize(300, 16777215))
        else:
            self.video.setFullScreen(True)


    # Ocultar y mostrar la lista de reproduccion
    def boton_menu(self):
        if self.lista_visible:
            self.lista.setVisible(False)
            size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
            self.marco.setSizePolicy(size_policy)
            self.lista_visible = False
        else:
            self.lista.setVisible(True)
            self.lista_visible = True

    # Metodos para arrastrar y soltar en la lista de reproduccion
    def dragEnterEvent(self, e):
        if e.mimeData().hasUrls():
            e.acceptProposedAction()

    # Metodos para arrastrar y soltar en la lista de reproduccion
    def dropEvent(self, e):
        for url in e.mimeData().urls():
            self.lista_repro.addMedia(QMediaContent(url))
        
        self.lista_repro.setPlaybackMode(QMediaPlaylist.Loop)

        self.media.setPlaylist(self.lista_repro)
        self.reproducir.setEnabled(True)
        self.reproductor.removeWidget(self.logo)

        self.media.play()

        self.modelo.layoutChanged.emit()

        """

        # If not playing, seeking to first of newly added + play.
        if self.media.state() != QMediaPlayer.PlayingState:
            #i = self.lista_repro.mediaCount() - len(e.mimeData().urls())
            #print(i)
            #self.lista_repro.setCurrentIndex(i)            
            self.reproducir.setEnabled(True)
            self.reproductor.removeWidget(self.logo)
            #self.media.setPlaylist(playlist)
            self.media.play() """

    # Metodo para cargar el video en cuestion
    def abrir_archivo(self):
        archivo, _ = QFileDialog.getOpenFileName(self, '   Abrir Archivo !!!', 'C:/Users/Duque/Videos', 'Solo Video (*.mp4 *.mov *.flv *.mkv *.ts *.mts *.avi);; Solo Audio (*.mp3 *.flac *.m4a *.wav)')

        if archivo != '':
            self.reproductor.removeWidget(self.logo)
            self.primera_reproduccion = False
            self.lista_repro.addMedia(QMediaContent(QUrl.fromLocalFile(archivo)))
            self.reproducir.setEnabled(True)

        self.modelo.layoutChanged.emit()

    # Metodo para el cambio en la lista de reproduccion
    def cambio_lista_repro(self, i):
        if i > -1:
            ix = self.modelo.index(i)
            self.lista.setCurrentIndex(ix)

    # Metodo para la seleccion en la lista de reproduccion
    def seleccion_lista_repro(self, ix):
        i = ix.indexes()[0].row()
        self.lista_repro.setCurrentIndex(i)

    # Metodo para silenciar el audio o video
    def silenciar(self):
        if self.media.isMuted():
            self.media.setMuted(False)
            icon = QIcon()
            icon.addPixmap(QPixmap(":/img/altavoz3.png"), QIcon.Normal, QIcon.Off)
            self.logo_volumen.setIcon(icon)
            self.logo_volumen.setToolTip(' Silenciar ')
        else:
            self.media.setMuted(True)
            icon = QIcon()
            icon.addPixmap(QPixmap(":/img/altavoz4.png"), QIcon.Normal, QIcon.Off)
            self.logo_volumen.setIcon(icon)
            self.logo_volumen.setToolTip(' Restablecer Sonido ')



    @pyqtSlot(str)
    def arrastrar_soltar(self, archivo):
        if archivo != '':
            self.media.setMedia(QMediaContent(QUrl.fromLocalFile(archivo)))
            self.reproducir.setEnabled(True)
            self.lista_repro.addMedia(QMediaContent(QUrl.fromLocalFile(archivo)))
            self.modelo.layoutChanged.emit()

    # Metodo para reproducir el video en cuestion
    def play_video(self):
        if self.primera_reproduccion:
            self.reproductor.removeWidget(self.logo)
            self.primera_reproduccion = False
        if self.media.state() == QMediaPlayer.PlayingState:
            self.media.pause()
        else:
            self.media.play()

    # Metodo que detecta el estado de cambio del boton reproducir de play a pausa y viceversa
    def cambios_video(self, state):
        if self.media.state() == QMediaPlayer.PlayingState:
            icon = QIcon()
            icon.addPixmap(QPixmap(":/img/pausa.png"), QIcon.Normal, QIcon.Off)
            self.reproducir.setIcon(icon)
            self.reproducir.setToolTip(' Pausar Video o Audio ')
            QToolTip.setFont(QFont('Cascadia Code PL', 18))   
        else:
            icon = QIcon()
            icon.addPixmap(QPixmap(":/img/play.svg"), QIcon.Normal, QIcon.Off)
            self.reproducir.setIcon(icon)
            self.reproducir.setToolTip(' Reproducir Video o Audio ')
            QToolTip.setFont(QFont('Cascadia Code PL', 18))


    def duracion_video(self, duracion):
        """
        # Detecta la duración del vídeo en el slider.
        """
        self.tiempo.setMaximum(duracion)
        self.total_duracion = duracion

    # Metodo que detecta la posiscion del video en el slider
    def posicion_video(self, posicion):

        if posicion >= 0:
            reproduccion = f'{detalle_tiempo(posicion)} || {detalle_tiempo(self.total_duracion)}'
            self.datos.setText(reproduccion)

        self.tiempo.blockSignals(True)
        self.tiempo.setValue(posicion)
        self.tiempo.blockSignals(False)


    # Metodo que detecta la posiscion establecida del modulo QMediaPlayer   
    def posicion_establecida(self, position):
        self.media.setPosition(position)

    def errores(self):
        self.reproducir.setEnabled(False)
        # self.lbl.setText("Error: " + self.media.errorString())

    # Metodo para centrar la ventana principal
    def centrar(self):
        ventana = self.frameGeometry()
        centro = QDesktopWidget().availableGeometry().center()
        # print(centro)
        ventana.moveCenter(centro)
        self.move(ventana.topLeft())
Beispiel #18
0
class MainWindowAction(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindowAction, self).__init__(parent)

        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()

        self.local_music_path = []

        self.setupUi(self)
        self.init()
        self.show()

    def init(self):
        # self.setWindowFlags(Qt.FramelessWindowHint)

        self.loadParams()

        self.playlist.setPlaybackMode(self.playlist.Loop)

        self.player.setPlaylist(self.playlist)
        self.player.play()

        exit_normal_icon_path = QUrl.fromLocalFile(EXIT_ICON_PATH)
        self.exit_normal_icon = QIcon(EXIT_ICON_PATH)

        self.exitButton.setStyleSheet(EXIT_BUTTON_STYLE)

        self.exitButton.clicked.connect(self.close)
        self.minButton.clicked.connect(self.showMinimized)
        # self.playButton.clicked.connect(self.playControl)

        self.nextButton.clicked.connect(self.playlist.next)
        self.prevButton.clicked.connect(self.playlist.previous)
        self.playButton.clicked.connect(self.controlPlay)

        self.player.currentMediaChanged.connect(self.initProgressBar)
        self.player.stateChanged.connect(self.changePlayState)
        self.player.positionChanged.connect(self.changeBar)

        self.playProgressBar.sliderReleased.connect(self.changePlayPosition)

    def loadParams(self):
        with open(CONFIG_PATH, 'r') as file:
            params = json.load(file)

            self.local_music_dirs = params['initParams']['LocalMusicDirs']
            last_playlist = params['lastPlayParams']['Playlist']

            self.initPlayList(last_playlist)

    def initPlayList(self, playlist_name):
        playlist_path = './PlayList/' + playlist_name + '.json'
        with open(playlist_path, 'r', encoding='UTF-8') as file:
            music_list = json.load(file)
            music_path_list = music_list['Songs']

        for music_path in music_path_list:
            path = QUrl.fromLocalFile(music_path)
            music = QMediaContent(path)
            self.playlist.addMedia(music)

    def controlPlay(self):
        if self.player.state() == self.player.PlayingState:
            self.player.pause()
            # self.playButton.setText("Play")
        elif self.player.state() == self.player.PausedState:
            self.player.play()
        elif self.player.state() == self.player.StoppedState:
            if self.player.mediaStatus() in [
                    self.player.LoadingMedia, self.player.LoadedMedia,
                    self.player.BufferedMedia, self.player.BufferingMedia
            ]:
                self.player.play()

    def changePlayState(self):
        if self.player.state() == self.player.PlayingState:
            self.playButton.setText("Pause")
        else:
            self.playButton.setText("Play")

    def initProgressBar(self):
        print(self.playlist.currentMedia().resources()[0].url().fileName())
        self.playProgressBar.setValue(0)

    def changeBar(self):

        if self.player.state() == self.player.PlayingState:
            duration = self.player.duration()
            if duration > 0:
                value = self.player.position() * 100 // duration
                self.playProgressBar.setValue(value)

    def changePlayPosition(self):
        self.player.pause()

        duration = self.player.duration()
        value = self.playProgressBar.value() * duration // 100

        self.player.setPosition(value)

        self.player.play()
Beispiel #19
0
class ApplicationWindow(QtWidgets.QMainWindow):
    global wavFileName
    global fig,chartFig
    global duration, counterClick
    global colorName, text_
    global startAnnotation, endTimeToPlay

    # >> QtMultimedia Signals
    #----------------------
    play = pyqtSignal()
    pause = pyqtSignal()
    stop = pyqtSignal()

    def __init__(self):
        global playerStarted
        global wavFileName, fig, chartFig
        global playerStarted, durationFlag, duration
        global colorName, text_, counterClick
        global startAnnotation, endTimeToPlay

        QtWidgets.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.main_widget = QtWidgets.QWidget(self)
        playerStarted = False

        #DEFINE PLAYER-PLAYLIST   
        #----------------------
        self.source = QtCore.QUrl.fromLocalFile(os.path.abspath(wavFileName))
        self.content = QMediaContent(self.source)
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist(self)
        self.playlist.addMedia(self.content)
        self.player.setPlaylist(self.playlist)

        # >> Define annotations and gantt chart 
        #---------------------- 
        self.wave = Waveform()
        fig = self.wave
        self.chart = Chart()
        chartFig = self.chart

        # >> Define player buttons 
        #---------------------- 
        playButton = QPushButton("Play")
        pauseButton = QPushButton("Pause")
        stopButton = QPushButton("Stop")

        # >> Define layouts 
        #---------------------- 
        waveLayout = QVBoxLayout()
        waveLayout.addWidget(self.wave)
        waveLayout.addWidget(self.chart)

        line = QFrame()
        line.setFrameShape(QFrame.VLine)
        line.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Expanding)
        waveLayout.addWidget(line)

        #Buttons layout
        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(playButton)
        buttonLayout.addWidget(pauseButton)
        buttonLayout.addWidget(stopButton)
        buttonLayout.setAlignment(Qt.AlignTop)


        # >> Specify final layout align 
        #----------------------
        layout = QHBoxLayout(self.main_widget)
        layout.addLayout(waveLayout)
        layout.addLayout(buttonLayout)
        
        # >> Define buttons connections 
        #---------------------- 
        playButton.clicked.connect(self.Play)
        pauseButton.clicked.connect(self.Pause)
        stopButton.clicked.connect(self.Stop)


        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)


    # PLAYER BUTTON FUNCTIONS

    # >> Play audio (whole signal or segment) 
    #---------------------- 
    def Play(self):
        global playerStarted
        global durationFlag
        global duration, counterClick
        global startTimeToPlay, endTimeToPlay, first

        #GET CLICKS FROM WAVEFORM
        #---------------------- 
        #Initialize connection-position ONCE
        if not playerStarted:
            #10ms for changePosition -> Not Delaying
            self.player.positionChanged.connect(self.checkPositionToStop)
            self.player.setNotifyInterval(10)
            if durationFlag==0:
                playerStarted = True
                startTimeToPlay = 0
                self.start = startTimeToPlay
                self.end = duration*1000 - 10
                endTimeToPlay = self.end
                counterClick = 3
            elif durationFlag==1:
                playerStarted = True
                self.start = startTimeToPlay
                self.end = duration*1000 - 10
                endTimeToPlay = self.end
                counterClick = 3
            elif durationFlag==2:
                playerStarted = True
                self.start = startTimeToPlay
                self.end = endTimeToPlay
            self.player.setPosition(self.start)

        playFlag = True
        self.player.play()

    # >> Pause audio playing 
    #----------------------
    def Pause(self):
        #Not begging from self.start
        playerStarted = True
        self.player.setPosition(self.time_)
        self.player.pause()

    # >> Stop audio playing 
    #----------------------
    def Stop(self):
        self.player.stop()
        #Begin again segment
        self.start = startTimeToPlay
        self.player.setPosition(self.start)

    # >> Check ms in audio to stop play 
    #----------------------
    def checkPositionToStop(self):
        self.time_ = self.player.position()
        print self.time_
        if self.time_ >= self.end:
            self.Stop()
            self.player.setPosition(self.start)

    def fileQuit(self):
        self.close()

    def closeEvent(self, ce):
        self.fileQuit()
Beispiel #20
0
appWindow.setLayout(grid)
appWindow.setGeometry(100, 100, 600, 600)

# Create a place to show a thumbnail of the last meal
lastMealImageLabel = QLabel()
#lastMealImage = None#QtGui.QPixmap('TestImage.jpeg')
lastMealImageLabel.setScaledContents(True)
#lastMealImageLabel.setPixmap(lastMealImage)
grid.addWidget(lastMealImageLabel, 0, 1)
lastMealImageLabel.show()

# Create a place to show video of the last Meal
mediaPlayer = QMediaPlayer()
mediaPlaylist = QMediaPlaylist(mediaPlayer)
videoWidget = QVideoWidget()
mediaPlayer.setPlaylist(mediaPlaylist)
mediaPlayer.setVideoOutput(videoWidget)
videoWidget.show()
grid.addWidget(videoWidget, 1, 1, 2, 1)

# Create a button to pull up the video of the last meal
mealLog = MealLog("log.txt")
mealSelector = QComboBox()
mealSelector.addItems(mealLog.getMeals())


def mealSelected(selectedMeal):
    meal = mealLog.getMeal(selectedMeal)
    mediaPlaylist.clear()
    videoFilePath = QFileInfo("MealVideos/{0}".format(
        meal.getVideoFileName())).absoluteFilePath()
class Window(QtWidgets.QDialog):

    def __init__(self):
        super().__init__()
        self.setGeometry(50, 50, 300, 400)
        self.setWindowTitle("Rolev Player")

# LIBRARY ROOT DIR FOLDER
        self.search_label = QtWidgets.QLabel("Select a music folder:", self)
        self.search_label.setGeometry(10, 5, 205, 10)

        self.btn_root_folder = QtWidgets.QPushButton("Browse", self)
        self.btn_root_folder.setGeometry(215, 20, 75, 25)

        # the text field of the currently selected root directory
        self.dir_text_field = QtWidgets.QLineEdit(self)
        self.dir_text_field.setGeometry(10, 20, 200, 25)

        self.btn_root_folder.clicked.connect(self.on_btn_root_folder)

# CURRENT MEDIA LABEL
        self.current_media_label = QtWidgets.QLabel("Now Playing: ", self)
        self.current_media_label.setGeometry(10, 260, 250, 15)

# CURRENT ALBUM COVER
        self.current_album_cover = QtWidgets.QLabel("Image", self)
        self.current_album_cover.setGeometry(10, 180, 75, 75)
        self.current_album_cover.setScaledContents(True)

# ARTIST DROP BOX
        self.artist_select_label = QtWidgets.QLabel("Artist", self)
        self.artist_select_label.setGeometry(10, 50, 250, 25)

        self.artist_select = QtWidgets.QComboBox(self)
        self.artist_select.setGeometry(10, 70, 250, 25)
        self.artist_select.activated[str].connect(self.on_artist_selection)

# ALBUMS DROP BOX
        self.album_select_label = QtWidgets.QLabel("Albums", self)
        self.album_select_label.setGeometry(10, 90, 250, 25)

        self.album_select = QtWidgets.QComboBox(self)
        self.album_select.setGeometry(10, 110, 250, 25)
        self.album_select.activated[str].connect(self.on_album_selection)

# SONGS DROP BOX
        self.song_select_label = QtWidgets.QLabel("Current Playlist", self)
        self.song_select_label.setGeometry(10, 130, 250, 25)

        self.song_select = QtWidgets.QComboBox(self)
        self.song_select.setGeometry(10, 150, 250, 25)
        self.song_select.activated[str].connect(self.on_song_selection)

# PLAYLIST
        self.playlist = QMediaPlaylist()
        self.playlist.currentIndexChanged.connect(self.meta_data_changed)

# MEDIA PLAYER
        self.player = QMediaPlayer()
        self.player.setPlaylist(self.playlist)
        self.player.playlist().setPlaybackMode(QMediaPlaylist.Loop)
        self.player.setVolume(50)

        self.player.durationChanged.connect(self.on_dur_change)
        self.player.positionChanged.connect(self.on_pos_change)

# VOLUME SLIDER
        self.slider_volume_label = QtWidgets.QLabel("Volume", self)
        self.slider_volume_label.setGeometry(10, 345, 50, 25)

        self.slider_volume = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
        self.slider_volume.setGeometry(60, 350, 130, 20)
        self.slider_volume.setRange(0, 100)
        self.slider_volume.setValue(50)
        self.slider_volume.valueChanged.connect(self.volume_change)

# PROGRESS SLIDER
        self.slider_progress_label = QtWidgets.QLabel("Progress", self)
        self.slider_progress_label.setGeometry(10, 315, 50, 25)

        self.slider_progress = QtWidgets.QSlider(QtCore.Qt.Horizontal, self)
        self.slider_progress.setGeometry(60, 320, 130, 20)
        self.slider_progress.sliderMoved.connect(self.progress_change)

# LYRICS SEARCH
        self.btn_lyrics = QtWidgets.QPushButton("Search\n Lyrics", self)
        self.btn_lyrics.setGeometry(220, 310, 70, 80)
        self.btn_lyrics.clicked.connect(self.on_lyrics)

# ALBUM INFO SEARCH
        self.btn_album_info = QtWidgets.QPushButton(
            "Search\nAlbum\nInfo", self)
        self.btn_album_info.setGeometry(105, 180, 75, 75)
        self.btn_album_info.clicked.connect(self.on_album_info)

# ARTIST INFO SEARCH
        self.btn_artist_info = QtWidgets.QPushButton(
            "Search\nArtist\nInfo", self)
        self.btn_artist_info.setGeometry(200, 180, 75, 75)
        self.btn_artist_info.clicked.connect(self.on_artist_info)

# PREV SONG BUTTON
        self.btn_prev = QtWidgets.QPushButton("Prev", self)
        self.btn_prev.setGeometry(10, 280, 75, 25)
        self.btn_prev.clicked.connect(self.on_btn_prev)

# NEXT SONG BUTTON
        self.btn_next = QtWidgets.QPushButton("Next", self)
        self.btn_next.setGeometry(200, 280, 75, 25)
        self.btn_next.clicked.connect(self.on_btn_next)

# PLAY/PAUSE BUTTON
        self.btn_play_pause = QtWidgets.QPushButton("Play", self)
        self.btn_play_pause.setGeometry(105, 280, 75, 30)
        self.btn_play_pause.clicked.connect(self.on_btn_play_pause)

        self.show()

    def on_btn_root_folder(self):
        self.root_dir = QtWidgets.QFileDialog().getExistingDirectory()
        self.dir_text_field.setText(self.root_dir)
        self.library = LibraryLoader.load_music_from_dir(
            self.dir_text_field.text())

        self.artist_select.clear()
        self.album_select.clear()
        self.song_select.clear()
        self.playlist.clear()

        self.btn_play_pause.setText("Play")
        self.artist_select.addItem("All Artists")
        for artist in self.library:
            self.artist_select.addItem(artist)
            for album in self.library[artist]:
                self.album_select.addItem(album)
        self.load_all_songs()

    def on_artist_selection(self):
        current_artist = self.artist_select.currentText()

        self.album_select.clear()
        self.song_select.clear()
        self.playlist.clear()

        self.btn_play_pause.setText("Play")
        self.album_select.addItem("All Albums")
        if current_artist == "All Artists":
            for artist in self.library:
                for album in self.library[artist]:
                    self.album_select.addItem(album)
            self.load_all_songs()
        else:
            for album in self.library[current_artist]:
                self.album_select.addItem(album)
            self.load_all_from_artist(current_artist)

    def load_all_songs(self):
        for artist in self.library:
            for album in self.library[artist]:
                for song in self.library[artist][album]:
                    self.song_select.addItem(song[0])
                    self.playlist.addMedia(
                        QMediaContent(QtCore.QUrl.fromLocalFile(song[1])))

    def load_all_from_artist(self, artist):
        for album in self.library[artist]:
            for song in self.library[artist][album]:
                self.song_select.addItem(song[0])
                self.playlist.addMedia(
                    QMediaContent(QtCore.QUrl.fromLocalFile(song[1])))

    def on_album_selection(self):
        current_artist = self.artist_select.currentText()
        current_album = self.album_select.currentText()
        self.song_select.clear()
        self.playlist.clear()
        self.btn_play_pause.setText("Play")
        if current_album == "All Albums" and current_artist == "All Artists":
            self.load_all_songs()

        elif current_album == "All Albums":
            self.load_all_from_artist(current_artist)

        elif current_artist == "All Artists":
            for artist in self.library:
                for album in self.library[artist]:
                    if album == self.album_select.currentText():
                        for song in self.library[artist][album]:
                            self.song_select.addItem(song[0])
                            self.playlist.addMedia(
                                QMediaContent(
                                    QtCore.QUrl.fromLocalFile(song[1])))
        else:
            for song in self.library[current_artist][current_album]:
                self.song_select.addItem(song[0])
                self.playlist.addMedia(
                    QMediaContent(QtCore.QUrl.fromLocalFile(song[1])))

    def on_song_selection(self):
        index = self.song_select.currentIndex()
        self.playlist.setCurrentIndex(index)

# GETTING THE CURRENT SONG METADATA
    # Returns a SONG OBJECT and not the current song title
    # For the title of the currently playing song use get_current_title()
    def get_current_song(self):
        curr_url = self.playlist.currentMedia().canonicalUrl().toString()[8:]
        if curr_url:
            return LibraryLoader.create_song(curr_url)

    def get_current_artist(self):
        if self.get_current_song() is not None:
            return self.get_current_song().artist

    def get_current_album(self):
        if self.get_current_song() is not None:
            return self.get_current_song().album

    def get_current_path(self):
        if self.get_current_song() is not None:
            return self.get_current_song().path

    def get_current_album_path(self):
        if self.get_current_path() is not None:
            return self.get_current_path().rsplit("/", 1)[0]

    def get_current_title(self):
        if self.get_current_song() is not None:
            return self.get_current_song().name

    def on_lyrics(self):
        if self.get_current_song() is not None:
            curr_artist = self.get_current_artist()
            curr_song = self.get_current_title()

            found_lyrics = RequestLyrics.search_song_lyrics(
                curr_artist, curr_song)
            choice = QtWidgets.QMessageBox.question(
                self, "Lyrics", found_lyrics[0],
                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
            if choice == QtWidgets.QMessageBox.Yes:
                webbrowser.open(found_lyrics[1])
        else:
            QtWidgets.QMessageBox.information(
                self, "Lyrics", "No lyrics found or no media is loaded!")

    def on_album_info(self):
        album = self.get_current_album()
        artist = self.get_current_artist()
        if (album is None) or (artist is None):
            print("Please, load a song first!")
        else:
            artist_info, album_info = AlbumArtwork.album_artist_info(
                artist, album)
            if album_info is not None:
                webbrowser.open(album_info)

    def on_artist_info(self):
        album = self.get_current_album()
        artist = self.get_current_artist()
        if (album is None) or (artist is None):
            print("Please, load a song first!")
        else:
            artist_info, album_info = AlbumArtwork.album_artist_info(
                artist, album)
            if artist_info is not None:
                webbrowser.open(artist_info)

    def on_btn_play_pause(self):
        if self.player.state() in (0, 2):
            self.player.play()
            if self.player.state() == 1:
                self.btn_play_pause.setText("Pause")
        else:
            self.player.pause()
            self.btn_play_pause.setText("Play")

    def on_btn_next(self):
        self.player.playlist().next()

    def on_btn_prev(self):
        self.player.playlist().previous()

    def on_dur_change(self, length):
        self.slider_progress.setMaximum(length)

    def on_pos_change(self, position):
        self.slider_progress.setValue(position)

    def volume_change(self):
        volume = self.slider_volume.value()
        self.player.setVolume(volume)

    def progress_change(self):
        position = self.slider_progress.value()
        self.player.setPosition(position)

    def meta_data_changed(self):

        now_playing = self.get_current_title()
        self.current_media_label.setText("Now Playing: " + now_playing)

        # Updating the currently playing album cover
        curr_album_path = self.get_current_album_path()
        curr_album = self.get_current_album()
        curr_artist = self.get_current_artist()
        cover_url = AlbumArtwork.album_cover(
            curr_album_path, curr_artist, curr_album)

        self.current_album_cover.setPixmap(QPixmap(cover_url))
        Scrobbler.scrobble(self.get_current_artist(), self.get_current_title())
Beispiel #22
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.curDictWord = None
        self.curWord = None
        self.curDictWordChange = False
        self.curDictWordLock = False

        self.ui = Ui_MainWindow_Ex()
        self.ui.setupUi(self)

        # hide progress bar
        self.ui.groupBox_5.setVisible(False)
        self.ui.groupBox_7.setVisible(False)

        # ---------------------------------
        # init dictionary
        self.dictionaries = [CambridgeUS(), CambridgeUK()]
        for obj in self.dictionaries:
            self.ui.dictBox.addItem(obj.displayname)
        self.ui.dictBox.currentIndexChanged.connect(self._dictionary_change)

        # connection
        self.ui.qwebView.loadStarted.connect(self._load_started)
        self.ui.qwebView.loadProgress.connect(self._load_progress)
        self.ui.qwebView.loadFinished.connect(self._load_finished)

        self.ui.refresh.clicked.connect(self._refresh_webview)
        self.ui.dictMktts.clicked.connect(self._refresh_mktts)
        # select dict
        self.ui.dictBox.setCurrentIndex(0)
        self._dictionary_change(0)

        # ---------------------------------
        # media play
        self.titlePlayer = QMediaPlayer(self)
        self.titlePlayer.stateChanged.connect(self._titleStateChanged)
        self.ui.titlePlay.clicked.connect(self._titlePlay)
        self.ui.titleStop.clicked.connect(self._titleStop)
        self.ui.titleMktts.clicked.connect(self._titleMktts)
        self.ui.titleEdit.textChanged.connect(self._titleTextChanged)

        self.contentPlayer = QMediaPlayer(self)
        self.contentPlayer.stateChanged.connect(self._contentStateChanged)
        self.ui.contentPlay.clicked.connect(self._contentPlay)
        self.ui.contentStop.clicked.connect(self._contentStop)
        self.ui.contentMktts.clicked.connect(self._contentMktts)
        self.ui.contentEdit.textChanged.connect(self._contentTextChanged)

        self.ui.tabBar.currentChanged.connect(self._tarbarChanged)
        self.update_dictword(None)

    def save_dictword_change(self):
        if self.curDictWordChange and self.curDictWord:
            self.curDictWord.save()

    def stop_voice_play(self):
        if self.titlePlayer.state() == QMediaPlayer.PlayingState:
            self.titlePlayer.stop()
            self.titlePlayer.setPlaylist(None)
        if self.contentPlayer.state() == QMediaPlayer.PlayingState:
            self.contentPlayer.stop()
            self.contentPlayer.setPlaylist(None)

    def update_dictword(self, dictwordobj):
        # if busy to mktts , don't update to cur dictword
        if self.curDictWordLock:
            return

        self.save_dictword_change()

        self.stop_voice_play()
        self.curDictWord = None
        self.curWord = None
        for i in range(self.ui.tabBar.count() - 1, -1, -1):
            self.ui.tabBar.removeTab(i)

        if dictwordobj is None:
            self.ui.queryword.setText('')
            self.ui.titleEdit.setPlainText('')
            self.ui.contentEdit.setPlainText('')
            self.ui.tabBar.setVisible(False)
            self.ui.titleEdit.setEnabled(False)
            self.ui.titlePlay.setEnabled(False)
            self.ui.titleStop.setEnabled(False)
            self.ui.titleMktts.setEnabled(False)
            self.ui.contentEdit.setEnabled(False)
            self.ui.contentPlay.setEnabled(False)
            self.ui.contentStop.setEnabled(False)
            self.ui.contentMktts.setEnabled(False)
        else:
            if len(dictwordobj.words) > 1:
                for w in dictwordobj.words:
                    self.ui.tabBar.addTab(w.name)
                self.ui.tabBar.setCurrentIndex(0)
                self.ui.tabBar.setVisible(True)
            else:
                self.ui.tabBar.setVisible(False)
            self.curDictWord = dictwordobj
            self.curWord = dictwordobj.words[0]
            self.ui.queryword.setText(self.curDictWord.query_word)
            self.ui.titleEdit.setPlainText(self.curWord.title_text)
            self.ui.contentEdit.setPlainText(self.curWord.content_text)
            self.ui.titleEdit.setEnabled(True)
            self.ui.titleMktts.setEnabled(True)
            self.ui.titlePlay.setEnabled(True)
            self.ui.titleStop.setEnabled(False)
            self.ui.contentEdit.setEnabled(True)
            self.ui.contentMktts.setEnabled(True)
            self.ui.contentPlay.setEnabled(True)
            self.ui.contentStop.setEnabled(False)

    @pyqtSlot(int)
    def _tarbarChanged(self, index):
        if self.curDictWord is None:
            return
        self.stop_voice_play()
        self.curWord = self.curDictWord.words[index]
        self.ui.titleEdit.setPlainText(self.curWord.title_text)
        self.ui.contentEdit.setPlainText(self.curWord.content_text)

        self.ui.titleEdit.setEnabled(True)
        self.ui.titleMktts.setEnabled(True)
        self.ui.titlePlay.setEnabled(True)
        self.ui.titleStop.setEnabled(False)
        self.ui.contentEdit.setEnabled(True)
        self.ui.contentMktts.setEnabled(True)
        self.ui.contentPlay.setEnabled(True)
        self.ui.contentStop.setEnabled(False)

    @pyqtSlot()
    def _titleTextChanged(self):
        if self.curDictWord is None:
            return
        txt = self.ui.titleEdit.toPlainText()
        self.curWord.title_text = txt
        self.curDictWordChange = True

    @pyqtSlot(bool)
    def _titlePlay(self, checked):
        if self.curDictWord is None:
            return
        self.stop_voice_play()
        if self.curWord.title_voices:
            mp3list = [os.path.join(self.curDictWord.data_path, fname) for fname in self.curWord.title_voices]
            playlist = QMediaPlaylist(self)
            for fmp3 in mp3list:
                playlist.addMedia(QUrl.fromLocalFile(fmp3))
            self.titlePlayer.setPlaylist(playlist)
            self.titlePlayer.play()

    @pyqtSlot(bool)
    def _titleStop(self, checked):
        self.stop_voice_play()

    @pyqtSlot(bool)
    def _titleMktts(self, checked):
        if self.curDictWord is None:
            return
        self.stop_voice_play()
        self.mk_voice(True)

    @pyqtSlot()
    def _contentTextChanged(self):
        if self.curDictWord is None:
            return
        txt = self.ui.contentEdit.toPlainText()
        self.curWord.content_text = txt
        self.curDictWordChange = True

    @pyqtSlot(bool)
    def _contentPlay(self, checked):
        if self.curDictWord is None:
            return
        self.stop_voice_play()
        if self.curWord.content_voices:
            mp3list = [os.path.join(self.curDictWord.data_path, fname) for fname in self.curWord.content_voices]
            playlist = QMediaPlaylist(self)
            for fmp3 in mp3list:
                playlist.addMedia(QUrl.fromLocalFile(fmp3))
            self.titlePlayer.setPlaylist(playlist)
            self.titlePlayer.play()

    @pyqtSlot(bool)
    def _contentStop(self, checked):
        self.stop_voice_play()

    @pyqtSlot(bool)
    def _contentMktts(self, checked):
        if self.curDictWord is None:
            return
        self.stop_voice_play()
        self.mk_voice(False)

    @pyqtSlot(QMediaPlayer.State)
    def _titleStateChanged(self, status):
        if status == QMediaPlayer.PlayingState:
            self.ui.titlePlay.setEnabled(False)
            self.ui.titleStop.setEnabled(True)
        else:
            self.ui.titlePlay.setEnabled(True)
            self.ui.titleStop.setEnabled(False)

    @pyqtSlot(QMediaPlayer.State)
    def _contentStateChanged(self, status):
        if status == QMediaPlayer.PlayingState:
            self.ui.contentPlay.setEnabled(False)
            self.ui.contentStop.setEnabled(True)
        else:
            self.ui.contentPlay.setEnabled(True)
            self.ui.contentStop.setEnabled(False)

    @pyqtSlot(int)
    def _dictionary_change(self, index):
        diobj = self.dictionaries[index]
        self.ui.accentBox.clear()

        lang = diobj.language
        default_ttslang = diobj.default_ttslang
        for k, v in tts_languages:
            if k.startswith(lang):
                self.ui.accentBox.addItem(v, k)
        for i in range(self.ui.accentBox.count()):
            k = self.ui.accentBox.itemData(i)
            if k == default_ttslang:
                self.ui.accentBox.setCurrentIndex(i)
                break
        else:
            self.ui.accentBox.setCurrentIndex(0)
        self.ui.qwebView.load(QUrl(diobj.home))

    @pyqtSlot(bool)
    def _refresh_webview(self, checked):
        self.ui.qwebView.reload()

    @pyqtSlot(bool)
    def _refresh_mktts(self, checked):
        url = self.ui.qwebView.page().url()
        index = self.ui.dictBox.currentIndex()
        diobj = self.dictionaries[index]
        qok, qword = diobj.check_url(url)
        if qok:
            tts_lang = self.ui.accentBox.currentData()
            dictwordobj, is_new = self.load_word(diobj, qword, tts_lang)
            if not is_new:
                dictwordobj.words.clear()
            func = partial(self.process, diobj, dictwordobj)
            self.ui.qwebView.page().toHtml(func)

    @pyqtSlot()
    def _load_started(self):
        self.ui.groupBox_7.setVisible(True)
        self.ui.dictBox.setEnabled(False)
        self.ui.accentBox.setEnabled(False)
        self.ui.dictMktts.setEnabled(False)

    @pyqtSlot(int)
    def _load_progress(self, val):
        self.ui.loadingBar.setValue(val)

    @pyqtSlot(bool)
    @except_check
    def _load_finished(self, bok):
        self.ui.groupBox_7.setVisible(False)
        self.ui.dictBox.setEnabled(True)
        self.ui.accentBox.setEnabled(True)
        self.ui.dictMktts.setEnabled(True)
        if bok:
            url = self.ui.qwebView.page().url()
            index = self.ui.dictBox.currentIndex()
            diobj = self.dictionaries[index]
            qok, qword = diobj.check_url(url)
            if qok:
                tts_lang = self.ui.accentBox.currentData()
                dictwordobj, is_new = self.load_word(diobj, qword, tts_lang)
                if is_new:
                    func = partial(self.process, diobj, dictwordobj)
                    self.ui.qwebView.page().toHtml(func)
                else:
                    self.update_dictword(dictwordobj)

    def closeEvent(self, event):
        """
        rewrite closeEvent, so when mainwindows closing, can clear up
        :param event:
        :return: None
        """
        AsyncTask.check_thread()
        self.save_dictword_change()

    def load_word(self, diobj, qword, tts_lang):
        """
        load dictobj, if don't exist then create it
        :param diobj:
        :param qword:
        :return: dictobj, is_new
        """
        data_path = os.path.join(data_dir, 'dictionaries', diobj.name, qword)
        if os.path.exists(data_path) and not os.path.isdir(data_path):
            raise RuntimeError("Loading failed: [%s] is'nt directory" % data_path)
        if os.path.exists(data_path):
            try:
                dictwordobj = DictWord.load(data_path)
                return dictwordobj, False
            except Exception as e:
                QMessageBox.warning(self, 'Warning', 'Loading failed: [%s], %s' % (data_path, str(e)))
        else:
            os.makedirs(data_path, exist_ok=True)
        dictwordobj = DictWord(data_path=data_path, tts_lang=tts_lang, query_word=qword)
        return dictwordobj, True

    @coroutine
    def process(self, diobj, dictwordobj, html):
        self.ui.groupBox_5.setVisible(True)
        try:
            info = '%s, parse html' % dictwordobj.query_word
            self.ui.progressBar.setValue(0)
            self.ui.progressLabel.setText(info)
            bok = yield AsyncTask(diobj.parse_html, dictwordobj, html)
            if not bok:
                dictwordobj.clear()
                info = '%s, parse failed!' % dictwordobj.query_word
                self.ui.progressBar.setValue(100)
                self.ui.progressLabel.setText(info)
                yield AsyncTask(time.sleep, 3)
                self.ui.groupBox_5.setVisible(False)
                return

            info = '%s, translate to voice ...' % dictwordobj.query_word
            self.ui.progressBar.setValue(10)
            self.ui.progressLabel.setText(info)
            total = 0
            for w in dictwordobj.words:
                if not w.title_voices and w.title_text:
                    total += 1
                if not w.content_voices and w.content_text:
                    total += 1
            cur = 0
            for w in dictwordobj.words:
                if not w.title_voices and w.title_text:
                    fname, fpath = dictwordobj.mk_voice_fname()
                    yield AsyncTask(trans_tts, w.title_text, fpath)
                    w.title_voices.append(fname)
                    cur += 1
                    progress = 10 + int(90 * cur / total)
                    self.ui.progressBar.setValue(progress)
                    self.ui.progressLabel.setText(info)
                if not w.content_voices and w.content_text:
                    fname, fpath = dictwordobj.mk_voice_fname()
                    yield AsyncTask(trans_tts, w.content_text, fpath)
                    w.content_voices.append(fname)
                    progress = 10 + int(90 * cur / total)
                    self.ui.progressBar.setValue(progress)
                    self.ui.progressLabel.setText(info)

        except (Exception, GeneratorExit):
            dictwordobj.clear()
            self.ui.groupBox_5.setVisible(False)
            raise

        info = '%s, finished!' % dictwordobj.query_word
        self.ui.progressBar.setValue(100)
        self.ui.progressLabel.setText(info)

        dictwordobj.save()
        self.ui.groupBox_5.setVisible(False)
        self.update_dictword(dictwordobj)
        return

    @coroutine(is_block=True)
    def mk_voice(self, is_title):
        self.curDictWordLock = True

        progressdlg = QProgressDialog('Mktts', parent=self)
        progressdlg.setWindowModality(Qt.WindowModal)
        progressdlg.setAutoClose(False)
        progressdlg.setAutoReset(False)
        progressdlg.setCancelButton(None)
        progressdlg.show()

        try:
            info = '%s, translate to voice ...' % self.curDictWord.query_word
            progressdlg.setLabelText(info)
            progressdlg.setValue(10)

            fname, fpath = self.curDictWord.mk_voice_fname()
            txt = self.curWord.title_text if is_title else self.curWord.content_text
            yield AsyncTask(trans_tts, txt, fpath)
            if is_title:
                self.curWord.title_voices = [fname]
            else:
                self.curWord.content_voices = [fname]

        except (Exception, GeneratorExit):
            self.curDictWordLock = False
            progressdlg.done(0)
            raise

        info = '%s, finished!' % self.curDictWord.query_word
        progressdlg.setLabelText(info)
        progressdlg.setValue(100)
        self.curDictWordChange = True
        self.curDictWordLock = False
        progressdlg.done(0)
        return
Beispiel #23
0
class VKwindow(QWidget):

    def __init__(self, vkapi):
        super().__init__()
        self.vk = vkapi
        self.initUI()

    def initUI(self):
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        self.setGeometry(300, 300, 290, 150)
        self.slider = QSlider(Qt.Horizontal)
        self.playBtn = QPushButton('►')
        self.nextBtn = QPushButton('>')
        self.prevBtn = QPushButton('<')

        self.nextBtn.clicked.connect(self.nextSong)
        self.prevBtn.clicked.connect(self.prevSong)

        self.playBtn.clicked.connect(self.playSong)
        self.setWindowTitle('VK music')
        self.list = QListWidget(self)
        self.list.currentItemChanged.connect(self.selectSong)

        for track in self.vk.method('audio.get').get('items'):
            self.list.addItem(SongWidgetItem(track))
            self.playlist.addMedia(QMediaContent(QUrl(track['url'])))

        hbox.addWidget(self.prevBtn)
        hbox.addWidget(self.playBtn)
        hbox.addWidget(self.nextBtn)
        hbox.addWidget(self.slider)

        self.player.setPlaylist(self.playlist)
        self.player.positionChanged.connect(self.setPosition)
        vbox.addWidget(self.list)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
        self.show()

    def selectSong(self, curr, prev):
        self.currentTrack = curr
        print(curr.getArtist())

    def playSong(self):
        print(self.currentTrack.getArtist())
        print(self.list.currentRow())
        if self.player.state() == QMediaPlayer.PlayingState and self.list.currentRow() == self.playlist.currentIndex():
            self.player.pause()
            return
        elif self.player.state() == QMediaPlayer.PausedState:
            self.player.play()
            return
        self.playlist.setCurrentIndex(self.list.currentRow())
        self.slider.setTickInterval(self.player.duration())
        self.player.play()

    def setPosition(self, pos):
        print(pos)
        self.slider.setTickPosition(pos)

    def nextSong(self):
        tmp = self.list.currentRow()
        size = self.list.count()
        tmp = (tmp + 1) % size
        self.list.setCurrentRow(tmp)
        self.playlist.setCurrentIndex(tmp)
        self.player.play()

    def prevSong(self):
        tmp = self.list.currentRow()
        size = self.list.count()
        tmp = (tmp - 1) % size
        self.list.setCurrentRow(tmp)
        self.playlist.setCurrentIndex(tmp)
        self.player.play()
Beispiel #24
0
class play(QMainWindow, Ui_Form):
    def __init__(self):
        super(play, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("VIP音乐播放器")
        self.m_filepath = 'E:/MusicMedia/MusicMedia/music/'
        # self.m_filepath = 'E:/ProgramData/PyUI/music'
        self.player = QMediaPlayer()
        self.PlayList = QMediaPlaylist()
        self.player.setPlaylist(self.PlayList)
        self.count = 0  #做一个计数器

    def search(self):
        self.listWidget_2.clear()
        music = self.lineEdit.text()  #地心
        author = self.lineEdit_2.text()  #汪峰
        self.music = search_song(music, author)
        self.music.song.connect(self.get_music)
        # 启动线程
        self.music.start()

    def get_music(self, data):
        if data != None:
            music = self.lineEdit.text()  # 地心
            self.listWidget_2.addItem("{} - {}".format(data[0], data[1]))
            #启动下载歌曲的线程
            self.dowm = download_song(music, data[1], data[2])
            # self.music.song.connect(self.music_dowm)   #没有信号的发送这里也可以不用定义槽函数
            self.dowm.start()
        else:
            music = self.lineEdit.text()  # 地心
            author = self.lineEdit_2.text()  # 汪峰
            # 启动下载歌曲的线程
            self.Intel = download_song2(music, author)
            self.Intel.song.connect(self.Intelnet_song)
            self.Intel.start()

    def Intelnet_song(self, data):
        self.listWidget_2.addItem("{} - {}".format(data['title'],
                                                   data['author']))
        # 启动下载歌曲的线程
        self.dowm = download_song(data['title'], data['author'], data['url'])
        self.dowm.start()

    def load_Local(self):
        if self.count == 0:
            self.PlayList.clear()  # 便于网络歌曲加入
            self.listWidget.clear()  # 刷新播放列表
            list = os.listdir(self.m_filepath)
            for cur_music in list:
                self.listWidget.addItem(cur_music[:-4])
                self.PlayList.addMedia(
                    QMediaContent(
                        QUrl.fromLocalFile(self.m_filepath + cur_music)))
            self.count += 1
        else:
            cur_music = self.listWidget_2.currentItem().text()
            row = self.listWidget.currentRow()
            self.listWidget.insertItem(row, cur_music)
            self.listWidget_2.clear()  # 清空在线的列表,造成一种从左边移动到右边的视觉
            self.PlayList.addMedia(
                QMediaContent(
                    QUrl.fromLocalFile(self.m_filepath + cur_music + '.mp3')))

    def custom_current_music(self):
        cur_music = self.listWidget.currentItem().text()  #获取当前播放的歌曲的名字
        item = self.listWidget.currentRow()
        self.PlayList.setCurrentIndex(item)
        self.player.play()  # 开始播放当前指定的歌曲

    def delete_song(self):
        cur_music = self.listWidget.currentItem().text()
        os.remove(self.m_filepath + cur_music + '.mp3')  #从磁盘上删除
        row = self.listWidget.currentRow()  #获取当前鼠标所选行
        self.listWidget.takeItem(row)  #从列表上删除该行
        self.PlayList.next()  #歌曲列表顺势往下
        self.player.play()  #播放

    # 重写窗口paintEvent函数
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawPixmap(self.rect(), QPixmap("image/back.jpg"))
Beispiel #25
0
class MusicPlayer(QMainWindow):
    """MusicPlayer houses all of elements that directly interact with the main window."""

    def __init__(self, parent=None):
        """Initialize the QMainWindow widget.

        The window title, window icon, and window size are initialized here as well
        as the following widgets: QMediaPlayer, QMediaPlaylist, QMediaContent, QMenuBar,
        QToolBar, QLabel, QPixmap, QSlider, QDockWidget, QListWidget, QWidget, and
        QVBoxLayout. The connect signals for relavant widgets are also initialized.
        """
        super(MusicPlayer, self).__init__(parent)
        self.setWindowTitle('Mosaic')

        window_icon = utilities.resource_filename('mosaic.images', 'icon.png')
        self.setWindowIcon(QIcon(window_icon))
        self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63)

        # Initiates Qt objects to be used by MusicPlayer
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.playlist_location = defaults.Settings().playlist_path
        self.content = QMediaContent()
        self.menu = self.menuBar()
        self.toolbar = QToolBar()
        self.art = QLabel()
        self.pixmap = QPixmap()
        self.slider = QSlider(Qt.Horizontal)
        self.duration_label = QLabel()
        self.playlist_dock = QDockWidget('Playlist', self)
        self.library_dock = QDockWidget('Media Library', self)
        self.playlist_view = QListWidget()
        self.library_view = library.MediaLibraryView()
        self.library_model = library.MediaLibraryModel()
        self.preferences = configuration.PreferencesDialog()
        self.widget = QWidget()
        self.layout = QVBoxLayout(self.widget)
        self.duration = 0
        self.playlist_dock_state = None
        self.library_dock_state = None

        # Sets QWidget() as the central widget of the main window
        self.setCentralWidget(self.widget)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.art.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)

        # Initiates the playlist dock widget and the library dock widget
        self.addDockWidget(defaults.Settings().dock_position, self.playlist_dock)
        self.playlist_dock.setWidget(self.playlist_view)
        self.playlist_dock.setVisible(defaults.Settings().playlist_on_start)
        self.playlist_dock.setFeatures(QDockWidget.DockWidgetClosable)

        self.addDockWidget(defaults.Settings().dock_position, self.library_dock)
        self.library_dock.setWidget(self.library_view)
        self.library_dock.setVisible(defaults.Settings().media_library_on_start)
        self.library_dock.setFeatures(QDockWidget.DockWidgetClosable)
        self.tabifyDockWidget(self.playlist_dock, self.library_dock)

        # Sets the range of the playback slider and sets the playback mode as looping
        self.slider.setRange(0, self.player.duration() / 1000)
        self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)

        # OSX system menu bar causes conflicts with PyQt5 menu bar
        if sys.platform == 'darwin':
            self.menu.setNativeMenuBar(False)

        # Initiates Settings in the defaults module to give access to settings.toml
        defaults.Settings()

        # Signals that connect to other methods when they're called
        self.player.metaDataChanged.connect(self.display_meta_data)
        self.slider.sliderMoved.connect(self.seek)
        self.player.durationChanged.connect(self.song_duration)
        self.player.positionChanged.connect(self.song_position)
        self.player.stateChanged.connect(self.set_state)
        self.playlist_view.itemActivated.connect(self.activate_playlist_item)
        self.library_view.activated.connect(self.open_media_library)
        self.playlist.currentIndexChanged.connect(self.change_index)
        self.playlist.mediaInserted.connect(self.initialize_playlist)
        self.playlist_dock.visibilityChanged.connect(self.dock_visiblity_change)
        self.library_dock.visibilityChanged.connect(self.dock_visiblity_change)
        self.preferences.dialog_media_library.media_library_line.textChanged.connect(self.change_media_library_path)
        self.preferences.dialog_view_options.dropdown_box.currentIndexChanged.connect(self.change_window_size)
        self.art.mousePressEvent = self.press_playback

        # Creating the menu controls, media controls, and window size of the music player
        self.menu_controls()
        self.media_controls()
        self.load_saved_playlist()

    def menu_controls(self):
        """Initiate the menu bar and add it to the QMainWindow widget."""
        self.file = self.menu.addMenu('File')
        self.edit = self.menu.addMenu('Edit')
        self.playback = self.menu.addMenu('Playback')
        self.view = self.menu.addMenu('View')
        self.help_ = self.menu.addMenu('Help')

        self.file_menu()
        self.edit_menu()
        self.playback_menu()
        self.view_menu()
        self.help_menu()

    def media_controls(self):
        """Create the bottom toolbar and controls used for media playback."""
        self.addToolBar(Qt.BottomToolBarArea, self.toolbar)
        self.toolbar.setMovable(False)

        play_icon = utilities.resource_filename('mosaic.images', 'md_play.png')
        self.play_action = QAction(QIcon(play_icon), 'Play', self)
        self.play_action.triggered.connect(self.player.play)

        stop_icon = utilities.resource_filename('mosaic.images', 'md_stop.png')
        self.stop_action = QAction(QIcon(stop_icon), 'Stop', self)
        self.stop_action.triggered.connect(self.player.stop)

        previous_icon = utilities.resource_filename('mosaic.images', 'md_previous.png')
        self.previous_action = QAction(QIcon(previous_icon), 'Previous', self)
        self.previous_action.triggered.connect(self.previous)

        next_icon = utilities.resource_filename('mosaic.images', 'md_next.png')
        self.next_action = QAction(QIcon(next_icon), 'Next', self)
        self.next_action.triggered.connect(self.playlist.next)

        repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png')
        self.repeat_action = QAction(QIcon(repeat_icon), 'Repeat', self)
        self.repeat_action.setShortcut('R')
        self.repeat_action.triggered.connect(self.repeat_song)

        self.toolbar.addAction(self.play_action)
        self.toolbar.addAction(self.stop_action)
        self.toolbar.addAction(self.previous_action)
        self.toolbar.addAction(self.next_action)
        self.toolbar.addAction(self.repeat_action)
        self.toolbar.addWidget(self.slider)
        self.toolbar.addWidget(self.duration_label)

    def file_menu(self):
        """Add a file menu to the menu bar.

        The file menu houses the Open File, Open Multiple Files, Open Playlist,
        Open Directory, and Exit Application menu items.
        """
        self.open_action = QAction('Open File', self)
        self.open_action.setShortcut('O')
        self.open_action.triggered.connect(self.open_file)

        self.open_multiple_files_action = QAction('Open Multiple Files', self)
        self.open_multiple_files_action.setShortcut('M')
        self.open_multiple_files_action.triggered.connect(self.open_multiple_files)

        self.open_playlist_action = QAction('Open Playlist', self)
        self.open_playlist_action.setShortcut('CTRL+P')
        self.open_playlist_action.triggered.connect(self.open_playlist)

        self.open_directory_action = QAction('Open Directory', self)
        self.open_directory_action.setShortcut('D')
        self.open_directory_action.triggered.connect(self.open_directory)

        self.save_playlist_action = QAction('Save Playlist', self)
        self.save_playlist_action.setShortcut('CTRL+S')
        self.save_playlist_action.triggered.connect(self.save_playlist)

        self.exit_action = QAction('Quit', self)
        self.exit_action.setShortcut('CTRL+Q')
        self.exit_action.triggered.connect(self.closeEvent)

        self.file.addAction(self.open_action)
        self.file.addAction(self.open_multiple_files_action)
        self.file.addAction(self.open_playlist_action)
        self.file.addAction(self.open_directory_action)
        self.file.addSeparator()
        self.file.addAction(self.save_playlist_action)
        self.file.addSeparator()
        self.file.addAction(self.exit_action)

    def edit_menu(self):
        """Add an edit menu to the menu bar.

        The edit menu houses the preferences item that opens a preferences dialog
        that allows the user to customize features of the music player.
        """
        self.preferences_action = QAction('Preferences', self)
        self.preferences_action.setShortcut('CTRL+SHIFT+P')
        self.preferences_action.triggered.connect(lambda: self.preferences.exec_())

        self.edit.addAction(self.preferences_action)

    def playback_menu(self):
        """Add a playback menu to the menu bar.

        The playback menu houses
        """
        self.play_playback_action = QAction('Play', self)
        self.play_playback_action.setShortcut('P')
        self.play_playback_action.triggered.connect(self.player.play)

        self.stop_playback_action = QAction('Stop', self)
        self.stop_playback_action.setShortcut('S')
        self.stop_playback_action.triggered.connect(self.player.stop)

        self.previous_playback_action = QAction('Previous', self)
        self.previous_playback_action.setShortcut('B')
        self.previous_playback_action.triggered.connect(self.previous)

        self.next_playback_action = QAction('Next', self)
        self.next_playback_action.setShortcut('N')
        self.next_playback_action.triggered.connect(self.playlist.next)

        self.playback.addAction(self.play_playback_action)
        self.playback.addAction(self.stop_playback_action)
        self.playback.addAction(self.previous_playback_action)
        self.playback.addAction(self.next_playback_action)

    def view_menu(self):
        """Add a view menu to the menu bar.

        The view menu houses the Playlist, Media Library, Minimalist View, and Media
        Information menu items. The Playlist item toggles the playlist dock into and
        out of view. The Media Library items toggles the media library dock into and
        out of view. The Minimalist View item resizes the window and shows only the
        menu bar and player controls. The Media Information item opens a dialog that
        shows information relevant to the currently playing song.
        """
        self.dock_action = self.playlist_dock.toggleViewAction()
        self.dock_action.setShortcut('CTRL+ALT+P')

        self.library_dock_action = self.library_dock.toggleViewAction()
        self.library_dock_action.setShortcut('CTRL+ALT+L')

        self.minimalist_view_action = QAction('Minimalist View', self)
        self.minimalist_view_action.setShortcut('CTRL+ALT+M')
        self.minimalist_view_action.setCheckable(True)
        self.minimalist_view_action.triggered.connect(self.minimalist_view)

        self.view_media_info_action = QAction('Media Information', self)
        self.view_media_info_action.setShortcut('CTRL+SHIFT+M')
        self.view_media_info_action.triggered.connect(self.media_information_dialog)

        self.view.addAction(self.dock_action)
        self.view.addAction(self.library_dock_action)
        self.view.addSeparator()
        self.view.addAction(self.minimalist_view_action)
        self.view.addSeparator()
        self.view.addAction(self.view_media_info_action)

    def help_menu(self):
        """Add a help menu to the menu bar.

        The help menu houses the about dialog that shows the user information
        related to the application.
        """
        self.about_action = QAction('About', self)
        self.about_action.setShortcut('H')
        self.about_action.triggered.connect(lambda: about.AboutDialog().exec_())

        self.help_.addAction(self.about_action)

    def open_file(self):
        """Open the selected file and add it to a new playlist."""
        filename, success = QFileDialog.getOpenFileName(self, 'Open File', '', 'Audio (*.mp3 *.flac)', '', QFileDialog.ReadOnly)

        if success:
            file_info = QFileInfo(filename).fileName()
            playlist_item = QListWidgetItem(file_info)
            self.playlist.clear()
            self.playlist_view.clear()
            self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(filename)))
            self.player.setPlaylist(self.playlist)
            playlist_item.setToolTip(file_info)
            self.playlist_view.addItem(playlist_item)
            self.playlist_view.setCurrentRow(0)
            self.player.play()

    def open_multiple_files(self):
        """Open the selected files and add them to a new playlist."""
        filenames, success = QFileDialog.getOpenFileNames(self, 'Open Multiple Files', '', 'Audio (*.mp3 *.flac)', '', QFileDialog.ReadOnly)

        if success:
            self.playlist.clear()
            self.playlist_view.clear()
            for file in natsort.natsorted(filenames, alg=natsort.ns.PATH):
                file_info = QFileInfo(file).fileName()
                playlist_item = QListWidgetItem(file_info)
                self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file)))
                self.player.setPlaylist(self.playlist)
                playlist_item.setToolTip(file_info)
                self.playlist_view.addItem(playlist_item)
                self.playlist_view.setCurrentRow(0)
                self.player.play()

    def open_playlist(self):
        """Load an M3U or PLS file into a new playlist."""
        playlist, success = QFileDialog.getOpenFileName(self, 'Open Playlist', '', 'Playlist (*.m3u *.pls)', '', QFileDialog.ReadOnly)

        if success:
            playlist = QUrl.fromLocalFile(playlist)
            self.playlist.clear()
            self.playlist_view.clear()
            self.playlist.load(playlist)
            self.player.setPlaylist(self.playlist)

            for song_index in range(self.playlist.mediaCount()):
                file_info = self.playlist.media(song_index).canonicalUrl().fileName()
                playlist_item = QListWidgetItem(file_info)
                playlist_item.setToolTip(file_info)
                self.playlist_view.addItem(playlist_item)

            self.playlist_view.setCurrentRow(0)
            self.player.play()

    def save_playlist(self):
        """Save the media in the playlist dock as a new M3U playlist."""
        playlist, success = QFileDialog.getSaveFileName(self, 'Save Playlist', '', 'Playlist (*.m3u)', '')
        if success:
            saved_playlist = "{}.m3u" .format(playlist)
            self.playlist.save(QUrl().fromLocalFile(saved_playlist), "m3u")

    def load_saved_playlist(self):
        """Load the saved playlist if user setting permits."""
        saved_playlist = "{}/.m3u" .format(self.playlist_location)
        if os.path.exists(saved_playlist):
            playlist = QUrl().fromLocalFile(saved_playlist)
            self.playlist.load(playlist)
            self.player.setPlaylist(self.playlist)

            for song_index in range(self.playlist.mediaCount()):
                file_info = self.playlist.media(song_index).canonicalUrl().fileName()
                playlist_item = QListWidgetItem(file_info)
                playlist_item.setToolTip(file_info)
                self.playlist_view.addItem(playlist_item)

            self.playlist_view.setCurrentRow(0)

    def open_directory(self):
        """Open the selected directory and add the files within to an empty playlist."""
        directory = QFileDialog.getExistingDirectory(self, 'Open Directory', '', QFileDialog.ReadOnly)

        if directory:
            self.playlist.clear()
            self.playlist_view.clear()
            for dirpath, __, files in os.walk(directory):
                for filename in natsort.natsorted(files, alg=natsort.ns.PATH):
                    file = os.path.join(dirpath, filename)
                    if filename.endswith(('mp3', 'flac')):
                        self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file)))
                        playlist_item = QListWidgetItem(filename)
                        playlist_item.setToolTip(filename)
                        self.playlist_view.addItem(playlist_item)

            self.player.setPlaylist(self.playlist)
            self.playlist_view.setCurrentRow(0)
            self.player.play()

    def open_media_library(self, index):
        """Open a directory or file from the media library into an empty playlist."""
        self.playlist.clear()
        self.playlist_view.clear()

        if self.library_model.fileName(index).endswith(('mp3', 'flac')):
            self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(self.library_model.filePath(index))))
            self.playlist_view.addItem(self.library_model.fileName(index))

        elif self.library_model.isDir(index):
            directory = self.library_model.filePath(index)
            for dirpath, __, files in os.walk(directory):
                for filename in natsort.natsorted(files, alg=natsort.ns.PATH):
                    file = os.path.join(dirpath, filename)
                    if filename.endswith(('mp3', 'flac')):
                        self.playlist.addMedia(QMediaContent(QUrl().fromLocalFile(file)))
                        playlist_item = QListWidgetItem(filename)
                        playlist_item.setToolTip(filename)
                        self.playlist_view.addItem(playlist_item)

        self.player.setPlaylist(self.playlist)
        self.player.play()

    def display_meta_data(self):
        """Display the current song's metadata in the main window.

        If the current song contains metadata, its cover art is extracted and shown in
        the main window while the track number, artist, album, and track title are shown
        in the window title.
        """
        if self.player.isMetaDataAvailable():
            file_path = self.player.currentMedia().canonicalUrl().toLocalFile()
            (album, artist, title, track_number, *__, artwork) = metadata.metadata(file_path)

            try:
                self.pixmap.loadFromData(artwork)
            except TypeError:
                self.pixmap = QPixmap(artwork)

            meta_data = '{} - {} - {} - {}' .format(track_number, artist, album, title)

            self.setWindowTitle(meta_data)
            self.art.setScaledContents(True)
            self.art.setPixmap(self.pixmap)
            self.layout.addWidget(self.art)

    def initialize_playlist(self, start):
        """Display playlist and reset playback mode when media inserted into playlist."""
        if start == 0:
            if self.library_dock.isVisible():
                self.playlist_dock.setVisible(True)
                self.playlist_dock.show()
                self.playlist_dock.raise_()

            if self.playlist.playbackMode() != QMediaPlaylist.Sequential:
                self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)
                repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png')
                self.repeat_action.setIcon(QIcon(repeat_icon))

    def press_playback(self, event):
        """Change the playback of the player on cover art mouse event.

        When the cover art is clicked, the player will play the media if the player is
        either paused or stopped. If the media is playing, the media is set
        to pause.
        """
        if event.button() == 1 and configuration.Playback().cover_art_playback.isChecked():
            if (self.player.state() == QMediaPlayer.StoppedState or
                    self.player.state() == QMediaPlayer.PausedState):
                self.player.play()
            elif self.player.state() == QMediaPlayer.PlayingState:
                self.player.pause()

    def seek(self, seconds):
        """Set the position of the song to the position dragged to by the user."""
        self.player.setPosition(seconds * 1000)

    def song_duration(self, duration):
        """Set the slider to the duration of the currently played media."""
        duration /= 1000
        self.duration = duration
        self.slider.setMaximum(duration)

    def song_position(self, progress):
        """Move the horizontal slider in sync with the duration of the song.

        The progress is relayed to update_duration() in order
        to display the time label next to the slider.
        """
        progress /= 1000

        if not self.slider.isSliderDown():
            self.slider.setValue(progress)

        self.update_duration(progress)

    def update_duration(self, current_duration):
        """Calculate the time played and the length of the song.

        Both of these times are sent to duration_label() in order to display the
        times on the toolbar.
        """
        duration = self.duration

        if current_duration or duration:
            time_played = QTime((current_duration / 3600) % 60, (current_duration / 60) % 60,
                                (current_duration % 60), (current_duration * 1000) % 1000)
            song_length = QTime((duration / 3600) % 60, (duration / 60) % 60, (duration % 60),
                                (duration * 1000) % 1000)

            if duration > 3600:
                time_format = "hh:mm:ss"
            else:
                time_format = "mm:ss"

            time_display = "{} / {}" .format(time_played.toString(time_format), song_length.toString(time_format))

        else:
            time_display = ""

        self.duration_label.setText(time_display)

    def set_state(self, state):
        """Change the icon in the toolbar in relation to the state of the player.

        The play icon changes to the pause icon when a song is playing and
        the pause icon changes back to the play icon when either paused or
        stopped.
        """
        if self.player.state() == QMediaPlayer.PlayingState:
            pause_icon = utilities.resource_filename('mosaic.images', 'md_pause.png')
            self.play_action.setIcon(QIcon(pause_icon))
            self.play_action.triggered.connect(self.player.pause)

        elif (self.player.state() == QMediaPlayer.PausedState or self.player.state() == QMediaPlayer.StoppedState):
            self.play_action.triggered.connect(self.player.play)
            play_icon = utilities.resource_filename('mosaic.images', 'md_play.png')
            self.play_action.setIcon(QIcon(play_icon))

    def previous(self):
        """Move to the previous song in the playlist.

        Moves to the previous song in the playlist if the current song is less
        than five seconds in. Otherwise, restarts the current song.
        """
        if self.player.position() <= 5000:
            self.playlist.previous()
        else:
            self.player.setPosition(0)

    def repeat_song(self):
        """Set the current media to repeat and change the repeat icon accordingly.

        There are four playback modes: repeat none, repeat all, repeat once, and shuffle.
        Clicking the repeat button cycles through each playback mode.
        """
        if self.playlist.playbackMode() == QMediaPlaylist.Sequential:
            self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
            repeat_on_icon = utilities.resource_filename('mosaic.images', 'md_repeat_all.png')
            self.repeat_action.setIcon(QIcon(repeat_on_icon))

        elif self.playlist.playbackMode() == QMediaPlaylist.Loop:
            self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
            repeat_on_icon = utilities.resource_filename('mosaic.images', 'md_repeat_once.png')
            self.repeat_action.setIcon(QIcon(repeat_on_icon))

        elif self.playlist.playbackMode() == QMediaPlaylist.CurrentItemInLoop:
            self.playlist.setPlaybackMode(QMediaPlaylist.Random)
            repeat_icon = utilities.resource_filename('mosaic.images', 'md_shuffle.png')
            self.repeat_action.setIcon(QIcon(repeat_icon))

        elif self.playlist.playbackMode() == QMediaPlaylist.Random:
            self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)
            repeat_icon = utilities.resource_filename('mosaic.images', 'md_repeat_none.png')
            self.repeat_action.setIcon(QIcon(repeat_icon))

    def activate_playlist_item(self, item):
        """Set the active media to the playlist item dobule-clicked on by the user."""
        current_index = self.playlist_view.row(item)
        if self.playlist.currentIndex() != current_index:
            self.playlist.setCurrentIndex(current_index)

        if self.player.state() != QMediaPlayer.PlayingState:
            self.player.play()

    def change_index(self, row):
        """Highlight the row in the playlist of the active media."""
        self.playlist_view.setCurrentRow(row)

    def minimalist_view(self):
        """Resize the window to only show the menu bar and audio controls."""
        if self.minimalist_view_action.isChecked():

            if self.playlist_dock.isVisible():
                self.playlist_dock_state = True
            if self.library_dock.isVisible():
                self.library_dock_state = True

            self.library_dock.close()
            self.playlist_dock.close()

            QTimer.singleShot(10, lambda: self.resize(500, 0))

        else:
            self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63)

            if self.library_dock_state:
                self.library_dock.setVisible(True)

            if self.playlist_dock_state:
                self.playlist_dock.setVisible(True)

    def dock_visiblity_change(self, visible):
        """Change the size of the main window when the docks are toggled."""
        if visible and self.playlist_dock.isVisible() and not self.library_dock.isVisible():
            self.resize(defaults.Settings().window_size + self.playlist_dock.width() + 6,
                        self.height())

        elif visible and not self.playlist_dock.isVisible() and self.library_dock.isVisible():
            self.resize(defaults.Settings().window_size + self.library_dock.width() + 6,
                        self.height())

        elif visible and self.playlist_dock.isVisible() and self.library_dock.isVisible():
            self.resize(defaults.Settings().window_size + self.library_dock.width() + 6,
                        self.height())

        elif (not visible and not self.playlist_dock.isVisible() and not
                self.library_dock.isVisible()):
            self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63)

    def media_information_dialog(self):
        """Show a dialog of the current song's metadata."""
        if self.player.isMetaDataAvailable():
            file_path = self.player.currentMedia().canonicalUrl().toLocalFile()
        else:
            file_path = None
        dialog = information.InformationDialog(file_path)
        dialog.exec_()

    def change_window_size(self):
        """Change the window size of the music player."""
        self.playlist_dock.close()
        self.library_dock.close()
        self.resize(defaults.Settings().window_size, defaults.Settings().window_size + 63)

    def change_media_library_path(self, path):
        """Change the media library path to the new path selected in the preferences dialog."""
        self.library_model.setRootPath(path)
        self.library_view.setModel(self.library_model)
        self.library_view.setRootIndex(self.library_model.index(path))

    def closeEvent(self, event):
        """Override the PyQt close event in order to handle save playlist on close."""
        playlist = "{}/.m3u" .format(self.playlist_location)
        if defaults.Settings().save_playlist_on_close:
            self.playlist.save(QUrl().fromLocalFile(playlist), "m3u")
        else:
            if os.path.exists(playlist):
                os.remove(playlist)
        QApplication.quit()
Beispiel #26
0
class Player(QWidget):

    fullScreenChanged = pyqtSignal(bool)

    def __init__(self, playlist, parent=None):
        super(Player, self).__init__(parent)

        self.colorDialog = None
        self.trackInfo = ""
        self.statusInfo = ""
        self.duration = 0

        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)

        self.player.durationChanged.connect(self.durationChanged)
        self.player.positionChanged.connect(self.positionChanged)
        self.player.metaDataChanged.connect(self.metaDataChanged)
        self.playlist.currentIndexChanged.connect(self.playlistPositionChanged)
        self.player.mediaStatusChanged.connect(self.statusChanged)
        self.player.bufferStatusChanged.connect(self.bufferingProgress)
        self.player.videoAvailableChanged.connect(self.videoAvailableChanged)
        self.player.error.connect(self.displayErrorMessage)

        self.videoWidget = VideoWidget()
        self.player.setVideoOutput(self.videoWidget)

        self.playlistModel = PlaylistModel()
        self.playlistModel.setPlaylist(self.playlist)

        self.playlistView = QListView()
        self.playlistView.setModel(self.playlistModel)
        self.playlistView.setCurrentIndex(
            self.playlistModel.index(self.playlist.currentIndex(), 0))

        self.playlistView.activated.connect(self.jump)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(0, self.player.duration() / 1000)

        self.labelDuration = QLabel()
        self.slider.sliderMoved.connect(self.seek)

        #        self.labelHistogram = QLabel()
        #        self.labelHistogram.setText("Histogram:")
        #        self.histogram = HistogramWidget()
        #        histogramLayout = QHBoxLayout()
        #        histogramLayout.addWidget(self.labelHistogram)
        #        histogramLayout.addWidget(self.histogram, 1)

        self.probe = QVideoProbe()
        #        self.probe.videoFrameProbed.connect(self.histogram.processFrame)
        self.probe.setSource(self.player)

        openButton = QPushButton("打开", clicked=self.open)

        controls = PlayerControls()
        controls.setState(self.player.state())
        controls.setVolume(self.player.volume())
        controls.setMuted(controls.isMuted())

        controls.play.connect(self.player.play)
        controls.pause.connect(self.player.pause)
        controls.stop.connect(self.player.stop)
        controls.next.connect(self.playlist.next)
        controls.previous.connect(self.previousClicked)
        controls.changeVolume.connect(self.player.setVolume)
        controls.changeMuting.connect(self.player.setMuted)
        controls.changeRate.connect(self.player.setPlaybackRate)
        controls.stop.connect(self.videoWidget.update)

        self.player.stateChanged.connect(controls.setState)
        self.player.volumeChanged.connect(controls.setVolume)
        self.player.mutedChanged.connect(controls.setMuted)

        self.fullScreenButton = QPushButton("全屏")
        self.fullScreenButton.setCheckable(True)

        self.colorButton = QPushButton("颜色选项")
        self.colorButton.setEnabled(False)
        self.colorButton.clicked.connect(self.showColorDialog)

        displayLayout = QHBoxLayout()
        displayLayout.addWidget(self.videoWidget, 2)
        displayLayout.addWidget(self.playlistView)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(openButton)
        controlLayout.addStretch(1)
        controlLayout.addWidget(controls)
        controlLayout.addStretch(1)
        controlLayout.addWidget(self.fullScreenButton)
        controlLayout.addWidget(self.colorButton)

        layout = QVBoxLayout()
        layout.addLayout(displayLayout)
        hLayout = QHBoxLayout()
        hLayout.addWidget(self.slider)
        hLayout.addWidget(self.labelDuration)
        layout.addLayout(hLayout)
        layout.addLayout(controlLayout)
        #        layout.addLayout(histogramLayout)

        self.setLayout(layout)

        if not self.player.isAvailable():
            QMessageBox.warning(
                self, "Service not available",
                "The QMediaPlayer object does not have a valid service.\n"
                "Please check the media service plugins are installed.")

            controls.setEnabled(False)
            self.playlistView.setEnabled(False)
            openButton.setEnabled(False)
            self.colorButton.setEnabled(False)
            self.fullScreenButton.setEnabled(False)

        self.metaDataChanged()

        self.addToPlaylist(playlist)

    def open(self):
        fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files")
        self.addToPlaylist(fileNames)

    def addToPlaylist(self, fileNames):
        for name in fileNames:
            fileInfo = QFileInfo(name)
            if fileInfo.exists():
                url = QUrl.fromLocalFile(fileInfo.absoluteFilePath())
                if fileInfo.suffix().lower() == 'm3u':
                    self.playlist.load(url)
                else:
                    self.playlist.addMedia(QMediaContent(url))
            else:
                url = QUrl(name)
                if url.isValid():
                    self.playlist.addMedia(QMediaContent(url))

    def durationChanged(self, duration):
        duration /= 1000

        self.duration = duration
        self.slider.setMaximum(duration)

    def positionChanged(self, progress):
        progress /= 1000

        if not self.slider.isSliderDown():
            self.slider.setValue(progress)

        self.updateDurationInfo(progress)

    def metaDataChanged(self):
        if self.player.isMetaDataAvailable():
            self.setTrackInfo(
                "%s - %s" % (self.player.metaData(QMediaMetaData.AlbumArtist),
                             self.player.metaData(QMediaMetaData.Title)))

    def previousClicked(self):
        # Go to the previous track if we are within the first 5 seconds of
        # playback.  Otherwise, seek to the beginning.
        if self.player.position() <= 5000:
            self.playlist.previous()
        else:
            self.player.setPosition(0)

    def jump(self, index):
        if index.isValid():
            self.playlist.setCurrentIndex(index.row())
            self.player.play()

    def playlistPositionChanged(self, position):
        self.playlistView.setCurrentIndex(self.playlistModel.index(
            position, 0))

    def seek(self, seconds):
        self.player.setPosition(seconds * 1000)

    def statusChanged(self, status):
        self.handleCursor(status)

        if status == QMediaPlayer.LoadingMedia:
            self.setStatusInfo("Loading...")
        elif status == QMediaPlayer.StalledMedia:
            self.setStatusInfo("Media Stalled")
        elif status == QMediaPlayer.EndOfMedia:
            QApplication.alert(self)
        elif status == QMediaPlayer.InvalidMedia:
            self.displayErrorMessage()
        else:
            self.setStatusInfo("")

    def handleCursor(self, status):
        if status in (QMediaPlayer.LoadingMedia, QMediaPlayer.BufferingMedia,
                      QMediaPlayer.StalledMedia):
            self.setCursor(Qt.BusyCursor)
        else:
            self.unsetCursor()

    def bufferingProgress(self, progress):
        self.setStatusInfo("Buffering %d%" % progress)

    def videoAvailableChanged(self, available):
        if available:
            self.fullScreenButton.clicked.connect(
                self.videoWidget.setFullScreen)
            self.videoWidget.fullScreenChanged.connect(
                self.fullScreenButton.setChecked)

            if self.fullScreenButton.isChecked():
                self.videoWidget.setFullScreen(True)
        else:
            self.fullScreenButton.clicked.disconnect(
                self.videoWidget.setFullScreen)
            self.videoWidget.fullScreenChanged.disconnect(
                self.fullScreenButton.setChecked)

            self.videoWidget.setFullScreen(False)

        self.colorButton.setEnabled(available)

    def setTrackInfo(self, info):
        self.trackInfo = info

        if self.statusInfo != "":
            self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo))
        else:
            self.setWindowTitle(self.trackInfo)

    def setStatusInfo(self, info):
        self.statusInfo = info

        if self.statusInfo != "":
            self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo))
        else:
            self.setWindowTitle(self.trackInfo)

    def displayErrorMessage(self):
        self.setStatusInfo(self.player.errorString())

    def updateDurationInfo(self, currentInfo):
        duration = self.duration
        if currentInfo or duration:
            currentTime = QTime((currentInfo / 3600) % 60,
                                (currentInfo / 60) % 60, currentInfo % 60,
                                (currentInfo * 1000) % 1000)
            totalTime = QTime((duration / 3600) % 60, (duration / 60) % 60,
                              duration % 60, (duration * 1000) % 1000)

            format = 'hh:mm:ss' if duration > 3600 else 'mm:ss'
            tStr = currentTime.toString(format) + " / " + totalTime.toString(
                format)
        else:
            tStr = ""

        self.labelDuration.setText(tStr)

    def showColorDialog(self):
        if self.colorDialog is None:
            brightnessSlider = QSlider(Qt.Horizontal)
            brightnessSlider.setRange(-100, 100)
            brightnessSlider.setValue(self.videoWidget.brightness())
            brightnessSlider.sliderMoved.connect(
                self.videoWidget.setBrightness)
            self.videoWidget.brightnessChanged.connect(
                brightnessSlider.setValue)

            contrastSlider = QSlider(Qt.Horizontal)
            contrastSlider.setRange(-100, 100)
            contrastSlider.setValue(self.videoWidget.contrast())
            contrastSlider.sliderMoved.connect(self.videoWidget.setContrast)
            self.videoWidget.contrastChanged.connect(contrastSlider.setValue)

            hueSlider = QSlider(Qt.Horizontal)
            hueSlider.setRange(-100, 100)
            hueSlider.setValue(self.videoWidget.hue())
            hueSlider.sliderMoved.connect(self.videoWidget.setHue)
            self.videoWidget.hueChanged.connect(hueSlider.setValue)

            saturationSlider = QSlider(Qt.Horizontal)
            saturationSlider.setRange(-100, 100)
            saturationSlider.setValue(self.videoWidget.saturation())
            saturationSlider.sliderMoved.connect(
                self.videoWidget.setSaturation)
            self.videoWidget.saturationChanged.connect(
                saturationSlider.setValue)

            layout = QFormLayout()
            layout.addRow("亮度", brightnessSlider)
            layout.addRow("对比度", contrastSlider)
            layout.addRow("色调", hueSlider)
            layout.addRow("饱和度", saturationSlider)

            button = QPushButton("关闭")
            layout.addRow(button)

            self.colorDialog = QDialog(self)
            self.colorDialog.setWindowTitle("颜色选项")
            self.colorDialog.setLayout(layout)

            button.clicked.connect(self.colorDialog.close)

        self.colorDialog.show()
Beispiel #27
0
class Window(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        # load config
        self.data = yaml_loader()

        # load ui
        self.setupUi(self)

        # load icons
        self.setWindowTitle("Sputofy")
        self.setWindowIcon(QIcon(os.path.join(RES_PATH, "logo.svg")))

        loopIcon = QIcon()
        loopIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "loopIconOFF.svg")))
        self.loopBtn.setIcon(loopIcon)
        prevIcon = QIcon()
        prevIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "backwardIcon.svg")))
        self.prevBtn.setIcon(prevIcon)
        playIcon = QIcon()
        playIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "playIcon.svg")))
        self.playBtn.setIcon(playIcon)
        nextIcon = QIcon()
        nextIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "forwardIcon.svg")))
        self.nextBtn.setIcon(nextIcon)
        randomIcon = QIcon()
        randomIcon.addPixmap(
            QPixmap(os.path.join(RES_PATH, "randomIconOFF.svg")))
        self.randomBtn.setIcon(randomIcon)
        volumeIcon = QIcon()
        volumeIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "volumeIcon.svg")))
        self.volumeBtn.setIcon(volumeIcon)

        # window's settings
        self.xCor = self.data['last_position']['xPos']
        self.yCor = self.data['last_position']['yPos']
        self.widthSize = self.data['last_window_size']['width']
        self.heightSize = self.data['last_window_size']['height']

        self.setGeometry(self.xCor, self.yCor, self.widthSize, self.heightSize)

        # load YouTubeToMP3
        self.YouTubeToMP3 = YouTubeToMP3Window()

        # open YouTubeToMP3 using button
        self.actionYT_MP3.triggered.connect(self.YouTubeToMP3.show_window)

        # info action
        self.actionInfo.triggered.connect(self.info_handle)

        #===========================  mediaplayer  ==============================

        # create media player object
        self.mediaPlayer = QMediaPlayer(None)

        # open button
        self.actionOpen_Song.triggered.connect(self.open_song)
        self.actionOpen_Folder.triggered.connect(self.open_folder)

        # play button
        self.playBtn.setEnabled(False)
        self.playBtn.clicked.connect(
            self.play_video
        )  # when btn is pressed: if it is playing it pause, if it is paused it plays
        # QShortcut(QKeySequence("Space"), self).activated.connect(self.play_video)metodo da ricordare in caso di problemi #TODO

        # duration slider
        self.durationSlider.setEnabled(False)
        self.durationSliderMaxValue = 0
        self.durationSlider.valueChanged.connect(
            self.mediaPlayer.setPosition
        )  # set mediaPlayer position using the value took from the slider
        QShortcut('Right', self, lambda: self.durationSlider.setValue(
            self.durationSlider.value() + 10000))  # 1s = 1000ms
        QShortcut('Left', self, lambda: self.durationSlider.setValue(
            self.durationSlider.value() - 10000))  # 1s = 1000ms
        QShortcut('Shift+Right', self, lambda: self.durationSlider.setValue(
            self.durationSliderMaxValue - 1000))  # jump to the end-1s of song
        QShortcut('Shift+Left', self,
                  lambda: self.durationSlider.setValue(0))  # restart song

        # volumeSlider
        self.volumeSlider.setProperty("value", 100)
        self.volumeSlider.setRange(0, 100)
        self.volumeSlider.setValue(
            self.data['volume']
            if self.data['volume'] != 0 else self.data['volume'] + 1
        )  # set slider value | if saved volume is equal to 0 load with volume = 1 else load the saved volume
        self.mediaPlayer.setVolume(
            self.data['volume']
            if self.data['volume'] != 0 else self.data['volume'] + 1
        )  # set mediaPlayer volume | if saved volume is equal to 0 load with volume = 1 else load the saved volume
        self.volumeLabel.setText(
            f"{self.data['volume']}%"
            if self.data['volume'] != 0 else f"{self.data['volume']+1}%"
        )  # set volume label text | if saved volume is equal to 0 load with volume = 1 else load the saved volume
        self.volumeSlider.valueChanged.connect(
            self.mediaPlayer.setVolume
        )  # set mediaPlayer volume using the value took from the slider

        QShortcut('Up', self, lambda: self.volumeSlider.setValue(
            self.volumeSlider.value() + 1))  # volume + 1
        QShortcut('Down', self, lambda: self.volumeSlider.setValue(
            self.volumeSlider.value() - 1))  # volume - 1

        QShortcut(
            'Shift+Up', self,
            lambda: self.volumeSlider.setValue(100))  # set maximum volume
        QShortcut(
            'Shift+Down', self,
            lambda: self.volumeSlider.setValue(0))  # set minimun volume(mute)

        # volumeBtn
        self.volumeBtn.clicked.connect(
            self.volume_toggle)  # mute/unmute volume pressing btn
        self.isMuted = False  # starting with a non-muted volume
        self.previousVolume = self.data[
            'volume']  # loading last registered volume

        # media player signals
        self.mediaPlayer.durationChanged.connect(
            self.duration_changed)  # set range of duration slider
        self.mediaPlayer.positionChanged.connect(
            self.position_changed)  # duration slider progress
        self.mediaPlayer.stateChanged.connect(
            self.player_state)  # see when it's playing or in pause
        self.mediaPlayer.volumeChanged.connect(
            self.volume_icon)  # change volumebtn icon

        #===========================  playlist  ==============================

        # create the playlist
        self.playlist = QMediaPlaylist()
        self.playlist.setPlaybackMode(2)
        self.mediaPlayer.setPlaylist(self.playlist)

        # clear the playlist
        self.playlistIsEmpty = True

        # playlistList model
        self.model = PlaylistModel(self.playlist)
        self.playlistView.setModel(self.model)
        self.playlist.currentIndexChanged.connect(
            self.playlist_position_changed)
        selection_model = self.playlistView.selectionModel()
        selection_model.selectionChanged.connect(
            self.playlist_selection_changed)

        #===========================  playlist function  ==============================

        self.mediaList = []  # array of loaded songs
        self.currentPlaylist = ""  # current loaded playlist name
        self.isCustomPlaylist = False

        # add song name on title
        self.playlist.currentMediaChanged.connect(self.set_title)

        # playlist buttons
        self.nextBtn.clicked.connect(self.next_song)  # seek track forward

        self.prevBtn.clicked.connect(self.prev_song)  # seek track backward

        self.mediaPlayer.mediaStatusChanged.connect(
            self.auto_next_track
        )  # once song is ended seek track forward and play it

        self.actionLoopIt.triggered.connect(
            self.loop_song)  # (1) loop the same song

        self.actionShuffle.triggered.connect(
            self.shuffle_playlist)  # change song's order

        self.loopBtn.clicked.connect(self.loop)  # (3) loop the playlist

        self.randomBtn.clicked.connect(
            self.random)  # (4) play random song without end

        # create new playlist
        self.actionCreatePlaylist.triggered.connect(self.custom_playlist)

        # delete current playlist
        self.actionDeletePlaylist.triggered.connect(self.delete_playlist)

        # remove all songs
        self.actionClearQueue.triggered.connect(self.clear_queue)

        # load playlist
        self.actionDict = {}  # dictionary of action Objects

        for action in self.data['playlistList']:
            self.actionDict[action] = self.menuPlaylist.addAction(
                action, partial(self.load_playlist, action))

        if len(self.data['playlistList']) == 0:
            self.menuPlaylist.menuAction().setVisible(False)

#================== Songs opening ==================#

    def open_folder(self):
        foldername = QFileDialog.getExistingDirectory(self, "Open folder",
                                                      "c:\\")

        if foldername:
            self.playlist.clear()
            self.mediaList.clear()

            for song in os.listdir(foldername):
                media = f"{foldername}/{song}"
                self.playlist.addMedia(QMediaContent(QUrl(media)))
                self.mediaList.append(media)

            self.playlist.setCurrentIndex(0)

            self.playBtn.setEnabled(True)
            self.durationSlider.setEnabled(True)

            self.playlistIsEmpty = False
            self.isCustomPlaylist = False

            self.model.layoutChanged.emit()  # load songs in list view
            self.set_title()

            self.mediaPlayer.pause()  # adjust play/pause icon

    def open_song(self):
        filename, _ = QFileDialog.getOpenFileName(self, "Open Song", "c:\\")

        if filename:
            if self.playlistIsEmpty == False:
                self.playlist.clear()
                self.mediaList.clear()
                self.playlistIsEmpty = True

            self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(filename)))
            self.mediaList.append(filename)

            self.playBtn.setEnabled(True)
            self.durationSlider.setEnabled(True)

            self.isCustomPlaylist = False

            self.model.layoutChanged.emit()  # load song in list view
            self.set_title()

            # adjust play/pause icon
            if self.playlist.mediaCount(
            ) == 1:  # if there is 1 song and you add another
                self.playlist.setCurrentIndex(0)
                self.mediaPlayer.pause()

    def load_playlist(self, playlistName):
        self.playlist.clear()
        self.mediaList.clear()

        # reload config
        self.data = yaml_loader()

        for song in self.data['playlistList'][playlistName]:
            self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(song)))
            self.mediaList.append(song)

        self.playlist.setCurrentIndex(0)

        self.playBtn.setEnabled(True)
        self.durationSlider.setEnabled(True)

        self.playlistIsEmpty = False
        self.isCustomPlaylist = True

        self.model.layoutChanged.emit()  # load songs in list view

        self.currentPlaylist = playlistName  # name of current loaded playlist
        self.set_title()

        self.statusbar.showMessage(f'Playlist "{playlistName}" loaded', 4000)
        self.menuPlaylist.menuAction().setVisible(True)

        # adjust play/pause icon
        self.mediaPlayer.pause()

    def set_title(self):
        if self.playlist.mediaCount() == 0:
            self.setWindowTitle("Sputofy")

        else:
            if self.isCustomPlaylist == False:
                self.setWindowTitle(
                    f"Sputofy - {os.path.splitext(self.playlist.currentMedia().canonicalUrl().fileName())[0]} - {self.playlist.currentIndex()+1}/{self.playlist.mediaCount()}"
                )
            else:
                self.setWindowTitle(
                    f"Sputofy - {self.currentPlaylist} - {os.path.splitext(self.playlist.currentMedia().canonicalUrl().fileName())[0]} - {self.playlist.currentIndex()+1}/{self.playlist.mediaCount()}"
                )

#=======================================================#

#================== Player Functions ==================#

    def play_video(self):
        if self.durationSlider.isEnabled():  # if slider was enabled
            if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
                self.mediaPlayer.pause()
            else:
                self.mediaPlayer.play()

    def duration_changed(self, duration):
        self.durationSlider.setRange(0, duration)

        if duration > 0:
            self.totalTime_Label.setText(time_format(round(
                duration / 1000)))  # duration is in ms
        self.durationSliderMaxValue = duration

    def position_changed(self, position):
        if position >= 0:
            self.elapsedTime_Label.setText(time_format(
                (position / 1000)))  # position is in ms

        # Disable the events to prevent updating triggering a setPosition event (can cause stuttering).
        self.durationSlider.blockSignals(True)
        self.durationSlider.setValue(position)
        self.durationSlider.blockSignals(False)

#=======================================================#

#================== Playlist Settings ==================#
#TODO Work in progress

    def playlist_array(self):
        index = self.playlist.mediaCount()
        mediaList = []
        for i in range(index):
            # songPath = (self.playlist.media(path).canonicalUrl().path())#.split("/",1)[1]
            # mediaList.append(songPath)
            # print(self.playlist.media(i).canonicalUrl().path())
            mediaList.append(self.playlist.media(i).canonicalUrl().fileName())
        return mediaList

    def custom_playlist(self):
        if not self.playlist.mediaCount() == 0:
            name, is_notEmpty = QInputDialog.getText(self, "playlist",
                                                     "save playlist as:")

            if name:

                if name in self.data['playlistList']:
                    self.statusbar.showMessage(
                        "playlist not created (name is already used)", 4000)
                else:
                    self.data['playlistList'][name] = self.mediaList
                    yaml_dump(self.data)

                    # add new action Object to dictionary
                    self.actionDict[name] = self.menuPlaylist.addAction(
                        name, partial(self.load_playlist, name))

                    self.load_playlist(
                        name)  # instantly loading the new playlist
            else:
                self.statusbar.showMessage(
                    "playlist not created (you should give a name to your baby :/)",
                    4000)
        else:
            self.statusbar.showMessage("there are no songs to playlist", 4000)

    def delete_playlist(self):
        if self.isCustomPlaylist:

            if len(self.data['playlistList']) == 1:
                self.menuPlaylist.menuAction().setVisible(False)

            self.data['playlistList'].pop(
                self.currentPlaylist)  # remove playlist from dictionary

            self.menuPlaylist.removeAction(self.actionDict[
                self.currentPlaylist])  # remove relative action
            self.actionDict.pop(
                self.currentPlaylist)  # remove relative action Object

            self.playlist.clear()
            self.model.layoutChanged.emit()
            self.setWindowTitle("Sputofy")

            yaml_dump(self.data)

            self.statusbar.showMessage(
                'succesfully deleted "' + self.currentPlaylist + '" playlist',
                4000)
        else:
            self.statusbar.showMessage("cannot delete a non custom playlist",
                                       4000)

    def clear_queue(self):
        self.playlist.clear()
        self.mediaList.clear()
        self.playBtn.setEnabled(False)
        self.model.layoutChanged.emit()

    def playlist_position_changed(self, i):
        if i > -1:
            ix = self.model.index(i)
            self.playlistView.setCurrentIndex(ix)

    def playlist_selection_changed(self, ix):
        # We receive a QItemSelection from selectionChanged.
        i = ix.indexes()[0].row()
        self.posizione = i
        self.playlist.setCurrentIndex(i)
        self.mediaPlayer.play()

#=======================================================#

#================== Playback Settings ==================#

    def next_song(self):
        if self.playlist.currentIndex() == self.playlist.mediaCount() - 1:
            self.playlist.setCurrentIndex(0)
        else:
            self.playlist.next()

    def prev_song(self):
        if self.playlist.currentIndex() == 0:
            self.playlist.setCurrentIndex(self.playlist.mediaCount() - 1)
        else:
            self.playlist.previous()

    def loop_song(self):
        if self.playlist.playbackMode() != 1:

            self.playlist.setPlaybackMode(1)

            self.actionLoopIt.setText("Loop it: ON")
            self.loopBtn.setIcon(
                QIcon(os.path.join(RES_PATH, "loopIconOFF.svg")))
            self.randomBtn.setIcon(
                QIcon(os.path.join(RES_PATH, "randomIconOFF.svg")))
        else:
            self.playlist.setPlaybackMode(2)
            self.actionLoopIt.setText("Loop it: OFF")

    def shuffle_playlist(self):
        if self.playlist.mediaCount():
            self.playlist.shuffle()
            self.model.layoutChanged.emit()
        else:
            self.statusbar.showMessage("there are no songs to shuffle", 4000)

    def loop(self):
        if self.playlist.playbackMode() != 3:
            self.playlist.setPlaybackMode(3)

            self.loopBtn.setIcon(
                QIcon(os.path.join(RES_PATH, "loopIconON.svg")))
            self.randomBtn.setIcon(
                QIcon(os.path.join(RES_PATH, "randomIconOFF.svg")))
            self.actionLoopIt.setText("Loop it: OFF")

        else:
            self.playlist.setPlaybackMode(2)
            self.loopBtn.setIcon(
                QIcon(os.path.join(RES_PATH, "loopIconOFF.svg")))

    def random(self):
        if self.playlist.playbackMode() != 4:
            self.playlist.setPlaybackMode(4)

            self.randomBtn.setIcon(
                QIcon(os.path.join(RES_PATH, "randomIconON.svg")))
            self.loopBtn.setIcon(
                QIcon(os.path.join(RES_PATH, "loopIconOFF.svg")))
            self.actionLoopIt.setText("Loop it: OFF")

        else:
            self.playlist.setPlaybackMode(2)
            self.randomBtn.setIcon(
                QIcon(os.path.join(RES_PATH, "randomIconOFF.svg")))

    def auto_next_track(self):

        if self.mediaPlayer.mediaStatus() == QMediaPlayer.EndOfMedia:
            if self.playlist.playbackMode() == 2:
                # index starts from 0       mediacount starts from 1
                if self.playlist.currentIndex(
                ) != self.playlist.mediaCount() - 1:
                    self.playlist.next()
                    self.mediaPlayer.play()
                else:  # if ended song was the last one set the index to the first one and pause
                    self.playlist.setCurrentIndex(0)
                    self.mediaPlayer.pause()

            # loop playlist
            elif self.playlist.playbackMode() == 3:
                self.playlist.next()
                self.mediaPlayer.play()

            # random song
            elif self.playlist.playbackMode() == 4:
                while self.playlist.previousIndex(
                ) == self.playlist.currentIndex(
                ):  # preventing repeating the same song
                    self.playlist.setCurrentIndex(
                        random.randint(0,
                                       self.playlist.mediaCount() - 1))

#=======================================================#

#================== Volume Settings ==================#

    def volume_icon(self, volume):

        self.volumeLabel.setText(f"{volume}%")

        if volume:
            volumeIcon = QIcon()
            volumeIcon.addPixmap(
                QPixmap(os.path.join(RES_PATH, "volumeIcon.svg")),
                QIcon.Normal, QIcon.Off)
            self.volumeBtn.setIcon(volumeIcon)
            self.previousVolume = self.volumeSlider.value()
            self.isMuted = False
        else:
            volumeMutedIcon = QIcon()
            volumeMutedIcon.addPixmap(
                QPixmap(os.path.join(RES_PATH, "volumeMutedIcon.svg")),
                QIcon.Normal, QIcon.Off)
            self.volumeBtn.setIcon(volumeMutedIcon)
            self.isMuted = True

    def volume_toggle(self):
        if self.isMuted == False:
            self.volumeSlider.setValue(0)
            self.isMuted = True

        elif self.isMuted == True:
            if self.previousVolume == 0:
                self.volumeSlider.setValue(10)
            else:
                self.volumeSlider.setValue(self.previousVolume)
            self.isMuted = False


#=======================================================#

    def mousePressEvent(self, event):
        ''' remove the border around the buttons created by using tab key '''

        focused_widget = QtWidgets.QApplication.focusWidget()
        try:
            focused_widget.clearFocus()
        except:
            pass
        QMainWindow.mousePressEvent(self, event)

    def player_state(self, event):
        ''' event handler that adjust the play/pause icon '''

        if event == QMediaPlayer.PlayingState:
            pauseIcon = QIcon()
            pauseIcon.addPixmap(
                QPixmap(os.path.join(RES_PATH, "pauseIcon.svg")), QIcon.Normal,
                QIcon.Off)
            self.playBtn.setIcon(pauseIcon)
        elif event == QMediaPlayer.PausedState:
            playIcon = QIcon()
            playIcon.addPixmap(QPixmap(os.path.join(RES_PATH, "playIcon.svg")),
                               QIcon.Normal, QIcon.Off)
            self.playBtn.setIcon(playIcon)

    def closeEvent(self, event):
        ''' event handler that take window information and save it in config before the window close '''

        # retrieve position
        xAxis = self.geometry().x()
        yAxis = self.geometry().y()

        self.data['last_position']['xPos'] = xAxis
        self.data['last_position']['yPos'] = yAxis

        # retrieve size
        width = self.width()
        height = self.height()

        self.data['last_window_size']['width'] = width
        self.data['last_window_size']['height'] = height

        # retrieve volume
        self.data['volume'] = self.mediaPlayer.volume()

        # retrieve user
        user = os.getlogin()
        self.data[
            'default_folder'] = f"C:\\Users\\{user}\\Desktop\\sputofy_songs"

        yaml_dump(self.data)

    def info_handle(self):

        info = "Sputofy\n1.0.0\n©2020 "+\
        "Sputofy is a free audio player based on the converted youtube songs made by a_str0\n\n"+\
        "Sputofy is written using python 3.x and PyQt5 modules"

        msg = QMessageBox.about(self, "About", info)
Beispiel #28
0
class Player(QWidget):
    def __init__(self, playlist=''):
        super().__init__()

        self.player = QMediaPlayer()
        self.wrapper = PlaylistWrapper("Untitled")
        self.playlist = self.wrapper.playlist
        self.player.setPlaylist(self.playlist)

        browseButton = QPushButton("Browse", clicked=self.crawl)
        saveButton = QPushButton("Save", clicked=self.save)
        loadButton = QPushButton("Load", clicked=self.load)
        addButton = QPushButton("Add song", clicked=self.add_song)
        nameButton = QPushButton("Name", clicked=self.name_playlist)

        controls = PlayerControls()

        controls.play.connect(self.player.play)
        controls.pause.connect(self.player.pause)
        controls.stop.connect(self.player.stop)
        controls.next.connect(self.playlist.next)
        controls.previous.connect(self.playlist.previous)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(browseButton)
        controlLayout.addWidget(saveButton)
        controlLayout.addWidget(loadButton)
        controlLayout.addWidget(addButton)
        controlLayout.addWidget(nameButton)
        controlLayout.addStretch(1)
        controlLayout.addWidget(controls)
        controlLayout.addStretch(1)

        self.displayLayout = QHBoxLayout()
        self.playlist_view = QListWidget()
        self.displayLayout.addWidget(self.playlist_view)

        self.layout = QVBoxLayout()
        self.layout.addLayout(self.displayLayout)
        self.layout.addLayout(controlLayout)
        self.layout.addLayout(self.displayLayout)
        self.setLayout(self.layout)
        self.setWindowTitle(
            "letTheMusicPlaY - {} Playlist".format(self.wrapper.name))

    def crawl(self):
        dir_name = QFileDialog.getExistingDirectory(self, "Browse here")
        crawler = MusicCrawler(dir_name)
        crawler.generate_playlist(self.wrapper)

        for song in self.wrapper.songs:
            self.playlist_view .addItem(
                "{} - {}".format(song.artist, song.title))

    def save(self):
        if self.wrapper.is_empty():
            box = QMessageBox()
            box.setText("Your playlist is empty")
            box.setWindowTitle("Sorry")
            box.exec_()
        else:
            dir_name = QFileDialog.getExistingDirectory(self, "Save here")
            self.wrapper.save(dir_name)

    def load(self):
        file_name, _ = QFileDialog.getOpenFileName(self, "Load from here")

        try:
            self.wrapper.load(file_name)
        except AssertionError:
            box = QMessageBox()
            box.setText("This is not a playlist")
            box.setWindowTitle("Sorry")
            box.exec_()

        for song in self.wrapper.songs:
            self.playlist_view .addItem(
                "{} - {}".format(song.artist, song.title))

    def add_song(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "Choose a song")
        try:
            self.wrapper.add_song(file_path)
            added_song = self.wrapper.path_to_song(file_path)
            self.playlist_view.addItem(
                "{} - {}".format(added_song.artist, added_song.title))
        except AssertionError:
            box = QMessageBox()
            box.setText("This is not file that I can open")
            box.setWindowTitle("Sorry")
            box.exec_()

    def name_playlist(self):
        new_name, _ = QInputDialog.getText(self, "Give name", "Enter name:")
        self.wrapper.name = new_name
        self.setWindowTitle(
            "letTheMusicPlaY - {} Playlist".format(self.wrapper.name))
Beispiel #29
0
class BasicVideoWidget(QVideoWidget):
    def __init__(self, *args, **kwargs):
        super(BasicVideoWidget, self).__init__(*args, **kwargs)
        self.mediaPlayer = QMediaPlayer(parent=self)
        self.setMediaObject(self.mediaPlayer)

        self.playlist = QMediaPlaylist()
        self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
        self.mediaPlayer.setPlaylist(self.playlist)

        self.mediaPlayer.positionChanged.connect(self._positionChanged)
        self.mediaPlayer.mutedChanged.connect(self.mutedChanged)
        self.mediaPlayer.durationChanged.connect(self._durationChanged)
        self.mediaPlayer.stateChanged.connect(self.stateChanged)
        self.mediaPlayer.seekableChanged.connect(self.seekableChanged)

    def loadUrl(self, url):
        mc = QMediaContent(url)
        self.playlist.clear()
        self.playlist.addMedia(mc)

    def load(self, path):
        self.loadUrl(QUrl.fromLocalFile(os.path.abspath(path)))

    @Slot()
    def play(self):
        self.mediaPlayer.play()

    @Slot()
    def pause(self):
        self.mediaPlayer.pause()

    @Slot()
    def stop(self):
        self.mediaPlayer.stop()

    @Slot(bool)
    def setMuted(self, b):
        self.mediaPlayer.setMuted(b)

    mutedChanged = Signal(bool)

    @Slot()
    def playPause(self):
        if self.mediaPlayer.state() != QMediaPlayer.PlayingState:
            self.mediaPlayer.play()
        else:
            self.mediaPlayer.pause()

    def state(self):
        return self.mediaPlayer.state()

    stateChanged = Signal(QMediaPlayer.State)

    def duration(self):
        return self.mediaPlayer.duration()

    durationChanged = Signal(int)

    @Slot(int)
    def setPosition(self, p):
        self.mediaPlayer.setPosition(p)

    def position(self):
        return self.mediaPlayer.position()

    @Slot('qint64')
    def _positionChanged(self, p):
        self.positionChanged.emit(p)

    positionChanged = Signal(int)

    @Slot('qint64')
    def _durationChanged(self, p):
        self.durationChanged.emit(p)

    seekableChanged = Signal(bool)

    def isSeekable(self):
        return self.mediaPlayer.isSeekable()
Beispiel #30
0
class MainWindow(QMainWindow):
    def __init__(self, app):
        super(MainWindow, self).__init__()
        self.app = app
        print('window created')
        self.setWindowIcon(QIcon('img/icon.png'))
        self.setWindowTitle('Kasino')
        self.setPalette(QPalette(Qt.darkGreen))
        self.setup_music()

        self.statusbar = QStatusBar(self)
        self.statusbar.setStyleSheet('background: white')
        self.setStatusBar(self.statusbar)
        self.statusbar.showMessage('Welcome to the Cassino game!')

        self.menubar = QMenuBar(self)
        self.optionsMenu = self.menubar.addMenu('Options')
        self.music_toggle = QAction()
        self.music_toggle.setText('Music')
        self.music_toggle.setShortcut('Ctrl+m')
        self.music_toggle.setCheckable(True)
        self.music_toggle.setChecked(True)
        self.optionsMenu.addAction(self.music_toggle)
        self.music_toggle.triggered.connect(self.toggle_music)

        self.speedGroup = QActionGroup(self)
        self.speedGroup.triggered.connect(self.set_speed)

        self.slow_speed = QAction('Slow', self.speedGroup)
        self.slow_speed.setCheckable(True)
        self.normal_speed = QAction('Normal', self.speedGroup)
        self.normal_speed.setCheckable(True)
        self.fast_speed = QAction('Fast', self.speedGroup)
        self.fast_speed.setCheckable(True)
        self.vfast_speed = QAction('Very Fast', self.speedGroup)
        self.vfast_speed.setCheckable(True)
        self.normal_speed.setChecked(True)

        self.speed_menu = self.optionsMenu.addMenu('Speed')
        self.speed_menu.addActions(self.speedGroup.actions())
        self.menubar.setMouseTracking(False)
        self.setMenuBar(self.menubar)

        self.play_widget = PlayWidget(self)
        self.main_menu = MainMenu(self)
        self.start_menu = StartMenu(self)
        self.widgets = QStackedWidget(self)
        self.widgets.addWidget(self.play_widget)
        self.widgets.addWidget(self.main_menu)
        self.widgets.addWidget(self.start_menu)
        self.widgets.setCurrentWidget(self.main_menu)

        self.setCentralWidget(self.widgets)
        self.setGeometry(25, 50, 1028, 720)

        self.main_menu.startbutton.clicked.connect(self.init_game)
        self.main_menu.loadbutton.clicked.connect(self.load_game)
        self.main_menu.quitbutton.clicked.connect(self.quit)
        self.play_widget.quit_button.clicked.connect(self.quit_to_menu)
        self.play_widget.save_button.clicked.connect(self.save_game)
        self.start_menu.startbutton.clicked.connect(self.start_game)

    def setup_music(self):
        self.music = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
        file_name = "sound/bg.mp3"
        self.media = QMediaContent(QUrl.fromLocalFile(file_name))
        self.playlist.addMedia(self.media)
        self.music.setPlaylist(self.playlist)
        self.music.setVolume(20)
        self.music.play()

    def toggle_music(self):
        if self.music.isMuted():
            self.music.setMuted(False)
            self.statusbar.showMessage('Music on', 5000)
        else:
            self.music.setMuted(True)
            self.statusbar.showMessage('Music off', 5000)

    def set_speed(self, action):
        if action == self.slow_speed:
            self.play_widget.speed = 1
        elif action == self.normal_speed:
            self.play_widget.speed = 3
        elif action == self.fast_speed:
            self.play_widget.speed = 4
        else:
            self.play_widget.speed = 6

    def start_game(self):
        self.play_widget.init_game(
            self.start_menu.extract_info_and_init_game())
        self.widgets.setCurrentWidget(self.play_widget)
        self.statusbar.showMessage('Game launched', 2000)

    def load_game(self):
        path = QFileDialog.getOpenFileName(self, 'Open save file',
                                           QDir.currentPath() + '/sav')[0]
        if path != '':
            game, msg, count = load(path)
            self.play_widget.resume_from_save(game, msg, count)
            self.widgets.setCurrentWidget(self.play_widget)
            self.statusbar.showMessage('Loaded save file', 5000)

    def save_game(self):
        path = QFileDialog.getSaveFileName(self, 'Create save file',
                                           QDir.currentPath() + '/sav')[0]
        if path != '':
            save(path, self.play_widget.game, self.play_widget.export_log(),
                 self.play_widget.move_count)
            self.statusbar.showMessage('Game saved', 5000)

    def init_game(self):
        self.widgets.setCurrentWidget(self.start_menu)
        self.statusbar.showMessage('Starting new game')

    def quit_to_menu(self):
        #Reset playwidget
        self.widgets.removeWidget(self.play_widget)
        speed = self.play_widget.speed
        self.play_widget.setParent(None)
        self.play_widget = PlayWidget(self)
        self.play_widget.speed = speed
        self.widgets.addWidget(self.play_widget)
        self.play_widget.quit_button.clicked.connect(self.quit_to_menu)
        self.play_widget.save_button.clicked.connect(self.save_game)

        self.widgets.setCurrentWidget(self.main_menu)

    def closeEvent(self, *args,
                   **kwargs):  #for handling closing from 'x' button
        self.quit()

    def quit(self):
        print('Exited game. Thanks for playing!\n')
        self.app.exit()
Beispiel #31
0
class DPlayerCore(QWidget):
    def __init__(self):
        """Initialize player and load playlist if any."""
        super().__init__()

        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)

        self.shuffling = False
        self.repeatingPlaylist = False
        self.repeatingSong = False

        self.musicOrder = []
        self.loadPlaylist(QUrl(
            'file://{}/lastListened.m3u'.format(os.getcwd())))

        self.lyricsApi = 'http://api.musixmatch.com/ws/1.1/'
        self.lyricsApiKey = '4b364f0652e471aa50813a22cdf830ea'
        self.lastFMapi = 'http://ws.audioscrobbler.com/2.0/'
        self.lastFMapikey = '052c43a00a4fc294bb3c9e0c38bdf710'
        self.lastFMsecret = '14c66392fa9c6c142a41ccc2b0674e19'
        self.username = None
        self.password = None
        self.network = None
        self.error = 'Something went wrong! Try again later.'

    def play(self):
        """Start the player."""
        self.player.play()

    def pause(self):
        """Pause the player."""
        self.player.pause()

    def stop(self):
        """Stop the player."""
        self.player.stop()

    def previous(self):
        """Play previous song."""
        self.playlist.previous()

    def next(self):
        """Play next song."""
        self.playlist.next()

    def mute(self):
        """Mute the player."""
        self.player.setMuted(True)

    def unmute(self):
        """Unmute the player."""
        self.player.setMuted(False)

    def setVolume(self, value):
        """Set player's volume to value."""
        self.player.setVolume(value)

    def add(self, fileNames):
        """Add fileNames to the playlist."""
        for name in fileNames:
            url = QUrl.fromLocalFile(QFileInfo(name).absoluteFilePath())
            self.playlist.addMedia(QMediaContent(url))
            self.musicOrder.append([name])

        self.added(len(fileNames))

    def added(self, added):
        """Saves music info in musicOrder."""
        for name, index in zip(
                self.musicOrder[self.playlist.mediaCount() - added:],
                range(self.playlist.mediaCount() - added,
                      len(self.musicOrder))):
            name = name[0]
            artist = self.getArtist(name)[0]
            title = self.getTitle(name)[0]
            album = self.getAlbum(name)[0]
            seconds = self.getDuration(name)
            duration = QTime(0, seconds // 60, seconds % 60)
            duration = duration.toString('mm:ss')
            self.musicOrder[index].extend(
                [artist, title, album, duration])

    def remove(self, songIndexes):
        """Remove songIndexes from the playlist."""
        for index in songIndexes:
            self.songChanged = True
            del self.musicOrder[index]
            self.playlist.removeMedia(index)
        self.songChanged = False

    def savePlaylist(self, path):
        """Save playlist to path."""
        if path.toString()[len(path.toString()) - 4:] != '.m3u':
            path = QUrl('{}.m3u'.format(path.toString()))
        self.playlist.save(path, 'm3u')

    def loadPlaylist(self, path):
        """Load playlist form path."""
        count = self.playlist.mediaCount()
        self.playlist.load(path)

        for index in range(count, self.playlist.mediaCount()):
            self.musicOrder.append(
                [self.playlist.media(index).canonicalUrl().path()])

        self.added(self.playlist.mediaCount() - count)

    def clearPlaylist(self):
        """Delete all songs in the playlist."""
        self.playlist.clear()
        self.musicOrder = []

    def shuffle(self, value):
        """Shuffle playlist if value = True."""
        self.shuffling = value

        if self.repeatingSong:
            return
        if self.shuffling:
            self.playlist.setPlaybackMode(QMediaPlaylist.Random)
        elif self.repeatingPlaylist:
            self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
        else:
            self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)

    def repeatPlaylist(self, value):
        """Repeat playlist after the last song is finished if value = True."""
        self.repeatingPlaylist = value

        if self.repeatingSong or self.shuffling:
            return
        if self.repeatingPlaylist:
            self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
        else:
            self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)

    def repeatSong(self, value):
        """Repeat current song if value = True."""
        self.repeatingSong = value

        if self.repeatingSong:
            self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        elif self.shuffling:
            self.playlist.setPlaybackMode(QMediaPlaylist.Random)
        elif self.repeatingPlaylist:
            self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
        else:
            self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)

    def sort(self, column, order):
        """Sort playlist by column in order."""
        ordered = sorted(self.musicOrder, key=itemgetter(column + 1),
                         reverse=order)

        self.clearPlaylist()
        for song in ordered:
            url = QUrl.fromLocalFile(QFileInfo(song[0]).absoluteFilePath())
            self.playlist.addMedia(QMediaContent(url))

        self.musicOrder = ordered

    def findLyrics(self, index):
        """Returns lyrics for song at index."""
        if self.musicOrder[index][2] == 'Unknown':
            return 'Unknown song.'

        searchSong = '{}track.search?q_track={}'.format(
            self.lyricsApi, self.musicOrder[index][2].replace(' ', '%20'))
        if self.musicOrder[index][1] != 'Unknown':
            searchSong = '{}&q_artist={}'.format(
                searchSong, self.musicOrder[index][1].replace(' ', '%20'))
        searchSong = '{}&f_has_lyrics=1&apikey={}'.format(
            searchSong, self.lyricsApiKey)

        try:
            requestSong = requests.get(searchSong)
        except requests.ConnectionError:
            return self.error

        songJson = requestSong.json()
        if requestSong.status_code != 200 or \
                songJson['message']['header']['available'] == 0:
            return self.error

        songId = songJson[
            'message']['body']['track_list'][0]["track"]["track_id"]
        searchLyrics = '{}track.lyrics.get?track_id={}&apikey={}'.format(
            self.lyricsApi, songId, self.lyricsApiKey)

        try:
            requestLyrics = requests.get(searchLyrics)
        except requests.ConnectionError:
            return self.error

        if requestLyrics.status_code != 200 or \
                songJson['message']['header']['available'] == 0:
            return self.error
        return requestLyrics.json()[
            'message']['body']['lyrics']['lyrics_body'][:-58]  # spam and bacon

    def findInfo(self, index):
        """Returns info about artist and album for index if any."""
        info = []

        if self.musicOrder[index][1] != 'Unknown':
            artist = self.artistInfo(self.musicOrder[index][1])
            if artist != self.error:
                info += artist

        if self.musicOrder[index][1] != 'Unknown' and \
                self.musicOrder[index][3] != 'Unknown':
            album = self.albumInfo(self.musicOrder[index][1],
                                   self.musicOrder[index][3])
            if album != self.error:
                info += album

        if info:
            return info
        else:
            return ['Unknown artist and song!']

    def artistInfo(self, artist):
        """Returns info about artist if any."""
        try:
            response = requests.get(
                ('{}/?method=artist.getinfo&artist={}&api_key={}&'
                    'format=json&autocorrect=1').format(
                    self.lastFMapi, artist, self.lastFMapikey))
        except Exception:
            return self.error

        if response.status_code != 200:
            return self.error

        artist = 'Artist: {}'.format(response.json()['artist']['name'])
        bio = 'Bio: {}'.format(
            response.json()['artist']['bio']['summary'].replace('.', '.\n'))
        spam = bio.find('<a')
        bio = bio[:spam]

        return [artist, bio]

    def albumInfo(self, artist, album):
        """Returns info about album if any."""
        try:
            response = requests.get(
                ('{}/?method=album.getinfo&artist={}&album={}&api_key={}&'
                    'format=json&autocorrect=1').format(
                    self.lastFMapi, artist, album, self.lastFMapikey))
        except Exception:
            return self.error

        if response.status_code != 200 or \
                'album' not in response.json().keys():
            return self.error

        album = 'Album: {}'.format(response.json()['album']['name'])
        tracks = ['Tracks: ']
        t = response.json()['album']['tracks']['track']
        for track, index in zip(t, range(len(t))):
            tracks.append('{}. {}'.format(index + 1, track['name']))

        info = [album, '\n'.join(tracks)]

        if 'wiki' in response.json()['album'].keys():
            wiki = response.json()['album']['wiki']
            if 'published' in wiki.keys():
                info.append('Published: {}'.format(wiki['published']))
            if 'summary' in wiki.keys():
                summary = wiki['summary'].replace('.', '.\n')
                spam = summary.find('<a')
                info.append('Summary: {}'.format(summary[:spam]))
            if 'Musical style' in wiki.keys():
                info.append('Musical style: {}'.format(wiki['Musical style']))

        return info

    def login(self, username, password):
        """Creates lastFM network."""
        self.username = username
        self.password = pylast.md5(password)
        try:
            self.network = pylast.LastFMNetwork(api_key=self.lastFMapikey,
                                                api_secret=self.lastFMsecret,
                                                username=self.username,
                                                password_hash=self.password)
        except Exception:
            self.username = None
            self.password = None
            self.network = None
            return False
        return True

    def logout(self):
        """Destoys lastFM network and current user info."""
        self.username = None
        self.password = None
        self.network = None

    def loveTrack(self, index):
        """Love track at index in lastFM."""
        if self.network is None:
            return False

        track = self.network.get_track(self.musicOrder[index][1],
                                       self.musicOrder[index][2])
        try:
            track.love()
        except Exception:
            return False
        return True

    def unloveTrack(self, index):
        """Unlove track at index in lastFM."""
        if self.network is None:
            return False

        track = self.network.get_track(self.musicOrder[index][1],
                                       self.musicOrder[index][2])
        try:
            track.unlove()
        except Exception:
            return False
        return True

    def isMuted(self):
        """Returns True if player is muted."""
        return self.player.isMuted()

    def getArtist(self, song):
        """Returns the artist of song."""
        if song[-4:] == '.mp3':
            obj = EasyID3(song)
            if 'artist' in obj.keys():
                return obj['artist']
        elif 'TAG' in mediainfo(song).keys():
            obj = mediainfo(song)['TAG']
            if 'artist' in obj.keys():
                return [obj['artist']]
            elif 'ARTIST' in obj.keys():
                return [obj['ARTIST']]
            else:
                return ['Unknown']
        else:
            return ['Unknown']

    def getTitle(self, song):
        """Returns the title of song."""
        if song[-4:] == '.mp3':
            obj = EasyID3(song)
            if 'title' in obj.keys():
                return obj['title']
        elif 'TAG' in mediainfo(song).keys():
            obj = mediainfo(song)['TAG']
            if 'title' in obj.keys():
                return [obj['title']]
            elif 'TITLE' in obj.keys():
                return [obj['TITLE']]
            else:
                return ['Unknown']
        else:
            return ['Unknown']

    def getAlbum(self, song):
        """Returns the album of song."""
        if song[-4:] == '.mp3':
            obj = EasyID3(song)
            if 'album' in obj.keys():
                return obj['album']
        elif 'TAG' in mediainfo(song).keys():
            obj = mediainfo(song)['TAG']
            if 'album' in obj.keys():
                return [obj['album']]
            elif 'ALBUM' in obj.keys():
                return [obj['ALBUM']]
            else:
                return ['Unknown']
        else:
            return ['Unknown']

    def getDuration(self, song):
        """Returns the duration of song."""
        if song[-4:] == '.mp3':
            return MP3(song).info.length
        return int(float(mediainfo(song)['duration']))
Beispiel #32
0
class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()

        uic.loadUi('ui/alarm_clock_form.ui', self)
        self.initUI()

        self.alarm_clock_list = []

        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        self.player.setPlaylist(self.playlist)

    def initUI(self):
        self.digital_clock = DigitalClock(self.clockWidget)
        self.digital_clock.time_tick.connect(self.time_tick)

        clock_widget_layout = QHBoxLayout()
        clock_widget_layout.addWidget(self.digital_clock)
        self.clockWidget.setLayout(clock_widget_layout)

        self.addAlarmClockButton.clicked.connect(self.add_alarm_clock)

    def closeEvent(self, event):

        reply = QMessageBox.question(self, 'Выход',
                                     "Вы уверены что хотите выйти? Будильники перестанут работать", 
                                     QMessageBox.Yes | QMessageBox.No, 
                                     QMessageBox.No)

        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def add_alarm_clock(self):
        dialog = NewAlarmClockDialog()
        dialog_result = dialog.exec_()

        if (dialog_result == QDialog.Accepted):
            widget_item = QListWidgetItem(self.listWidget);

            alarm_clock_item = AlarmClockItem(dialog.nameLineEdit.text(), 
                                            dialog.timeEdit.time(),
                                            dialog.filePathLineEdit.text())
            alarm_clock_item.alarm.connect(self.alarm)
            self.alarm_clock_list.append(alarm_clock_item)

            alarm_clock_item_widget = AlarmClockItemWidget(alarm_clock_item, widget_item, self)
            alarm_clock_item_widget.alarm_clock_remove.connect(self.alarm_clock_remove)
            
            widget_item.setSizeHint(alarm_clock_item_widget.sizeHint());
            self.listWidget.setItemWidget(widget_item, alarm_clock_item_widget);
        
        dialog.deleteLater()

    def alarm_clock_remove(self):
        self.listWidget.takeItem(self.listWidget.row(self.sender().list_widget_item))
        self.alarm_clock_list.remove(self.sender().alarm_clock)

    def time_tick(self):
        for alarm_clock in self.alarm_clock_list:
            if alarm_clock.is_active:
                alarm_clock.tick()

    def alarm(self):
        alarm_clock = self.sender()

        self.play_sound(alarm_clock.alarm_sound)

        QMessageBox.information(self, 'Будильник',
                                     'Будильник "' + alarm_clock.title + '"', 
                                     QMessageBox.Ok)
        alarm_clock.is_alarm = False
        self.stop_sound()

    def play_sound(self, sound):
        if len(sound):
            self.player.stop()
            self.playlist.clear()

            media_content = QMediaContent(QUrl.fromLocalFile(sound))
            self.playlist.addMedia(media_content)
            self.player.play()

    def stop_sound(self):
        self.player.stop()
Beispiel #33
0
# 播放列表
playlist = QMediaPlaylist()

_list = []
for i in range(1, 12):
    print("../data/lolita/voice/kiana_%d.mp3" % i)
    _list.append(QMediaContent(QUrl("../data/lolita/voice/kiana_%d.mp3" % i)))
playlist.addMedia(_list)
# 只播放当前的
playlist.setPlaybackMode(QMediaPlaylist.CurrentItemOnce)


player = QMediaPlayer()
# 设置播放列表
player.setPlaylist(playlist)
# 设置音量
player.setVolume(100)

def play():
    playlist.setCurrentIndex(2)
    player.play()
    playlist.setCurrentIndex(0)
#     currentIndex = playlist.currentIndex() + 1
#     print(currentIndex)
#     if currentIndex > playlist.mediaCount():
#         currentIndex = 0
#     playlist.setCurrentIndex((currentIndex))
#     player.play()

btn = QPushButton("play", clicked = play)
Beispiel #34
0
class VideoPlayer(QWidget):
    def __init__(self, parent=None):
        # Super (whatever that means)
        super(VideoPlayer, self).__init__()
        # Initialize
        self.setGeometry(400, 100, 1280, 960)
        self.setWindowTitle('ProjecTosh by Trent Baker (c) 2019')

        # Set window background color
        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(53, 64, 38))
        self.setPalette(p)

        # UI and widgets and such
        # Video widget
        self.video = QVideoWidget()
        #self.video.resize(300, 300)
        #self.video.move(0, 0)

        # Media Playlist
        self.playlist = QMediaPlaylist()
        self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile("video/video.avi"))) # https://www.nps.gov/grca/learn/photosmultimedia/b-roll_hd07.htm (default is public domain b-roll video)
        self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
        self.playlist.setCurrentIndex(0)

        # Video player widget
        self.player = QMediaPlayer()
        self.player.setPlaylist(self.playlist)
        self.player.setVideoOutput(self.video)
        #self.player.setMedia()
        self.player.play()

        # Label widgets
        fnt = QtGui.QFont('Impact', 20)
        h = announcements.announcements[1][0]
        b = announcements.announcements[1][1]
        # Announcements body
        self.lbAnnounce = QLabel()
        self.lbAnnounce.setText(h+'\n\n'+b)
        self.lbAnnounce.setFont(fnt)
        self.lbAnnounce.setAlignment(Qt.AlignTop)
        self.lbAnnounce.setWordWrap(True)
        self.lbAnnounce.setMaximumSize(600, 400)
        self.lbAnnounce.setStyleSheet("color: rgb(250, 241, 205);")
        # Current day
        self.lbDay = QLabel()
        self.lbDay.setText("it's day 1 lol")
        self.lbDay.setAlignment(Qt.AlignCenter)
        # Grad events
        self.lbGrad = QLabel()
        self.lbGrad.setText('upcoming grad event:\nsled')
        self.lbGrad.setAlignment(Qt.AlignCenter)

        # Timer for cycling announcement
        i = 1
        j = 1
        # Called when timer hits limit
        def handler():
            nonlocal h, b, i, j # Here i is the 'x' index of the 2D announcements.announcements array, and j is the 'y'
            j += 1
            # Print attempt begin
            print("Trying announcement at index "+str(i))
            # Cycle fake for loop
            if j >= len(announcements.announcements[i]):
                j = 1
                i += 1
            if i >= len(announcements.announcements):
                i = 1
            # Try until get announcement
            error = True
            while error:
                try:
                    h = announcements.announcements[i][0]
                    b = announcements.announcements[i][j] # At present this is only listing the first non-title item in the annoucement lists
                    ann = h + '\n\n' + b
                    print("Successfully updated announcement from index "+str(i))
                    error = False
                except:
                    print("Error when converting announcement at index "+str(i)+", skipping")
                    i += 1
            # Update announcement text
            self.lbAnnounce.setText(ann)
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(handler)
        self.timer.start(2000)

        # Do the layout move to do the layout move
        self.grid = QGridLayout()
        w = 4
        h = 3
        wl = 2
        wr = w-wl
        ht = 1
        hb = h-ht
        self.grid.addWidget(self.lbDay, 0, 0, ht, wl)
        self.grid.addWidget(self.lbGrad, ht, 0, hb, wl)
        self.grid.addWidget(self.video, 0, wl, ht, wr)
        self.grid.addWidget(self.lbAnnounce, ht, wl, hb, wr)

        self.setLayout(self.grid)
Beispiel #35
0
class Player(Qt.QWidget):
    """docstring for Player"""
    fullScreenChanged = Qt.pyqtSignal(bool)

    def __init__(self, playlist, parent=None):
        # create player
        super(Player, self).__init__(parent)

        self.trackInfo = ''
        self.statusInfo = ''
        self.duration = 0

        # create player object
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.name = 'Current playlist'
        self.player.setPlaylist(self.playlist)

        self.player.durationChanged.connect(self.durationChanged)
        self.player.positionChanged.connect(self.positionChanged)
        self.player.metaDataChanged.connect(self.metaDataChanged)
        self.playlist.currentIndexChanged.connect(self.playlistPositionChanged)

        self.player.mediaStatusChanged.connect(self.statusChanged)
        self.player.bufferStatusChanged.connect(self.bufferingProgress)
        # self.player.videoAvailableChanged.connect(self.videoAvailableChanged)
        self.player.error.connect(self.displayErrorMessage)

        # connect with VideoWidget
        # self.videoWidget = VideoWidget()
        # self.player.setVideoOutput(self.videoWidget)

        # connect with PlaylistModel
        self.playlistModel = PlaylistModel()
        self.playlistModel.setPlaylist(self.playlist)

        self.playlistView = Qt.QListView()
        self.playlistView.setModel(self.playlistModel)
        self.playlistView.setCurrentIndex(self.playlistModel.index(
            self.playlist.currentIndex(), 0))

        # change to next song
        self.playlistView.activated.connect(self.jump)

        self.slider = Qt.QSlider(QtCore.Qt.Horizontal)
        self.slider.setRange(0, self.player.duration() / 1000)

        self.labelDuration = Qt.QLabel()
        self.slider.sliderMoved.connect(self.seek)

        # create histogram
        self.labelHistogram = Qt.QLabel()
        self.labelHistogram.setText('Histogram: ')
        self.histogram = HistogramWidget()
        histogramLayout = Qt.QHBoxLayout()
        histogramLayout.addWidget(self.labelHistogram)
        histogramLayout.addWidget(self.histogram, 1)

        # create videoProbe
        self.videoProbe = Qt.QVideoProbe()
        self.videoProbe.videoFrameProbed.connect(self.histogram.processFrame)
        self.videoProbe.setSource(self.player)

        # add control
        controls = Controllers()
        controls.setState(self.player.state())
        controls.setVolume(self.player.volume())
        controls.setMuted(controls.isMuted())

        # connect player's controls with Controllers
        controls.play.connect(self.player.play)
        controls.pause.connect(self.player.pause)
        controls.stop.connect(self.player.stop)
        controls.next.connect(self.playlist.next)
        controls.previous.connect(self.previousAction)
        controls.changeVolume.connect(self.player.setVolume)
        controls.changeMuting.connect(self.player.setMuted)
        # setPlaybackRate is from QMediaPlayer
        controls.changeSpeed.connect(self.player.setPlaybackRate)
        # controls.stop.connect(self.videoWidget.update)

        self.player.stateChanged.connect(controls.setState)
        self.player.volumeChanged.connect(controls.setVolume)
        self.player.mutedChanged.connect(controls.setMuted)

        # create fullScreenButton
        # self.fullScreenButton = Qt.QPushButton('FullScreen')
        # self.fullScreenButton.setCheckable(True)

        # displayLayout
        displayLayout = Qt.QHBoxLayout()
        # displayLayout.addWidget(self.videoWidget, 2)
        displayLayout.addWidget(self.playlistView)

        # controlLayout
        controlLayout = Qt.QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        # connect controlLayout with controls
        controlLayout.addWidget(controls)
        controlLayout.addStretch(1)
        # connect controlLayout with fullScreenButton
        # controlLayout.addWidget(self.fullScreenButton)

        # visualize player
        layout = Qt.QVBoxLayout()
        layout.addLayout(displayLayout)

        # layout for sliding song playing
        hLayout = Qt.QHBoxLayout()
        hLayout.addWidget(self.slider)
        hLayout.addWidget(self.labelDuration)

        layout.addLayout(hLayout)
        layout.addLayout(controlLayout)
        layout.addLayout(histogramLayout)

        # set icon
        self.setWindowIcon(Qt.QIcon('favicon.ico'))

        # create menus
        toolBar = Qt.QToolBar()

        # create basic actions
        self.createActions()

        # create simple button to repeat song
        self.repeatButton = Qt.QToolButton()
        self.repeatButton.setDefaultAction(self.repeatAct)

        # create playOnceButton
        self.playOnceButton = Qt.QToolButton()
        self.playOnceButton.setDefaultAction(self.playOnceAct)
        self.playOnceButton.setEnabled(False)

        # create shuffleButton
        self.shuffleButton = Qt.QToolButton()
        self.shuffleButton.setDefaultAction(self.shuffleAct)

        # create sequentialButton
        self.sequentialButton = Qt.QToolButton()
        self.sequentialButton.setDefaultAction(self.sequentialAct)

        # create fileButton for fileMenu
        fileButton = Qt.QToolButton()
        fileButton.setText('File')
        fileButton.setPopupMode(Qt.QToolButton.MenuButtonPopup)
        fileButton.setMenu(self.popFileMenu())

        # create editButton for editMenu
        closeButton = Qt.QToolButton()
        closeButton.setText('Edit')
        closeButton.setDefaultAction(self.fileCloseAct)

        # display in toolBar these buttons
        toolBar.addWidget(self.repeatButton)
        toolBar.addWidget(self.playOnceButton)
        toolBar.addWidget(self.shuffleButton)
        toolBar.addWidget(self.sequentialButton)
        toolBar.addWidget(fileButton)
        toolBar.addWidget(closeButton)

        # add toolBar to layout of the player
        layout.addWidget(toolBar)
        layout.addWidget(Qt.QGroupBox())

        self.setWindowTitle("Python Music Player")
        self.setLayout(layout)

        if not self.player.isAvailable():
            Qt.QMessageBox(self, 'Unavailable service')
            # self.displayErrorMessage()
            controls.setEnabled(False)
            self.playlistView.setEnabled(False)
            self.fullScreenButton.setEnabled(False)

        self.metaDataChanged()

        self.addToPlaylist(playlist)

    # create fileMenu
    def popFileMenu(self):
        aMenu = Qt.QMenu(self)
        aMenu.addAction(self.fileOpenAct)
        aMenu.addAction(self.fileCloseAct)
        return aMenu

    def createActions(self):
        self.repeatAct = Qt.QAction('Repeat', self, triggered=self.repeatSong)
        self.playOnceAct = Qt.QAction(
            'Play once', self, triggered=self.playOnceSong)
        self.shuffleAct = Qt.QAction(
            'Shuffle', self, triggered=self.playlist.shuffle)
        self.sequentialAct = Qt.QAction(
            'Sequential', self, triggered=self.playSequential)
        self.fileOpenAct = Qt.QAction('Open', self, triggered=self.open)
        self.fileOpenAct.setShortcut('Ctrl+O')

        self.fileCloseAct = Qt.QAction('Close', self, triggered=self.close)
        self.fileCloseAct.setShortcut('Ctrl+Q')

    def repeatSong(self):
        self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)
        self.repeatButton.setEnabled(False)
        self.playOnceButton.setEnabled(True)

    def playOnceSong(self):
        self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)
        self.playOnceButton.setEnabled(False)
        self.repeatButton.setEnabled(True)

    # unproperly used
    def playSequential(self):
        self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)

    # get and display song duration
    def durationChanged(self, duration):
        duration /= 1000

        self.duration = duration
        self.slider.setMaximum(duration)

    # change slider position
    def positionChanged(self, progress):
        progress /= 1000

        if not self.slider.isSliderDown():
            self.slider.setValue(progress)

        self.updateDurationInfo(progress)

    def updateDurationInfo(self, currentInfo):
        duration = self.duration
        if currentInfo or duration:
            currentTime = QtCore.QTime(
                (currentInfo / 3600) % 60,  # hours
                (currentInfo / 60) % 60,  # minutes
                currentInfo % 60,  # seconds
                (currentInfo * 1000) % 1000)  # miliseconds
            totalTime = QtCore.QTime(
                (duration / 3600) % 60,  # hours
                (duration / 60) % 60,  # minutes
                duration % 60,  # seconds
                (duration * 1000) % 1000)  # miliseconds
            formating = 'hh:mm:ss' if duration > 3600 else 'mm:ss'
            toString = (currentTime.toString(formating) + ' / ' +
                        totalTime.toString(formating))
        else:
            toString = ''

        self.labelDuration.setText(toString)

    def metaDataChanged(self):
        if self.player.isMetaDataAvailable():
            self.setTrackInfo('{0} - {1}'.format(
                self.player.metaData(Qt.QMediaMetaData.AlbumArtist),
                self.player.metaData(Qt.QMediaMetaData.Title)))

    def setTrackInfo(self, info):
        self.trackInfo = info

        if self.statusInfo:
            self.setWindowTitle('{0} | {1}'.format(
                self.trackInfo, self.statusInfo))
        else:
            self.setWindowTitle(self.trackInfo)

    def playlistPositionChanged(self, position):
        self.playlistView.setCurrentIndex(
            self.playlistModel.index(position, 0))

    def statusChanged(self, status):
        self.handleCursor(status)

        if status == QMediaPlayer.LoadingMedia:
            self.setStatusInfo('Loading...')
        elif status == QMediaPlayer.StalledMedia:
            self.setStatusInfo('Media Stalled')
        elif status == QMediaPlayer.EndOfMedia:
            Qt.QApplication.alert(self)
        elif status == QMediaPlayer.InvalidMedia:
            self.displayErrorMessage()
        else:
            self.setStatusInfo('')

    def handleCursor(self, status):
        if status in [QMediaPlayer.LoadingMedia, QMediaPlayer.BufferingMedia,
                      QMediaPlayer.StalledMedia]:
            self.setCursor(QtCore.Qt.BusyCursor)
        else:
            self.unsetCursor()

    def setStatusInfo(self, info):
        self.statusInfo = info

        if self.statusInfo:
            self.setWindowTitle('{0} | {1}'.format(
                self.trackInfo, self.statusInfo))
        else:
            self.setWindowTitle(self.trackInfo)

    def bufferingProgress(self, progress):
        self.setStatusInfo('Buffering {0}'.format(progress))

    def displayErrorMessage(self):
        self.statusInfo(self.player.errorString())

    def jump(self, index):
        if index.isValid():
            self.playlist.setCurrentIndex(index.row())
            self.player.play()

    def seek(self, seconds):
        self.player.setPosition(seconds * 1000)

    def previousAction(self):
        self.playlist.previous()

    def close(self):
        choice = Qt.QMessageBox.question(
            self,
            'Close',
            'Close the app?',
            Qt.QMessageBox.Yes | Qt.QMessageBox.No)

        if choice == Qt.QMessageBox.Yes:
            sys.exit()

    def open(self):
        names, _ = Qt.QFileDialog.getOpenFileNames(self, 'Open Files')
        # ['/home/milka/Documents/MusicPlayer/song.mp3']
        self.addToPlaylist(names)

    def addToPlaylist(self, names):
        for name in names:
            fileInfo = Qt.QFileInfo(name)
            if fileInfo.exists():
                url = QtCore.QUrl.fromLocalFile(fileInfo.absoluteFilePath())

                # save_to_db song url
                create_song(
                    url.path(), self.duration, playlist_name=self.name)

                if fileInfo.suffix().lower() == 'm3u':
                    self.playlist.load(url)
                else:
                    self.playlist.addMedia(Qt.QMediaContent(url))
            else:
                url = QtCore.QUrl(name)
                if url.isValid():
                    self.playlist.addMedia(Qt.QMediaContent(url))
class Player(QMediaPlayer):
    def __init__(self, parent=None):
        super(Player, self).__init__(parent)
        self.parent = parent
        self.player = QMediaPlayer()
        self.queueList = QMediaPlaylist()
        self.player.setPlaylist(self.queueList)
        self.queueData = []
        self.position = 0
        self.volume = 100

        self.player.mediaStatusChanged.connect(self.qmp_mediaStatusChanged)
        self.player.positionChanged.connect(self.qmp_positionChanged)
        self.player.durationChanged.connect(self.durationChanged)
        self.queueList.currentIndexChanged.connect(self.playlistPosChanged)

    def add(self, data):
        """Add track to the queue"""
        queueData = {
            'pc_title': data['pc_title'],
            'title': data['title'],
            'url': data['url'],
            'date': data['date_format'],
            'description': data['description']
        }
        self.queueData.append(queueData)
        self.queueList.addMedia(QMediaContent(QUrl(data['url'])))

    def playPause(self):
        icon = QIcon.fromTheme("media-playback-pause")

        if self.player.state() == QMediaPlayer.StoppedState:
            if self.player.mediaStatus() == QMediaPlayer.NoMedia:
                if self.queueList.mediaCount() != 0:
                    self.player.play()
            elif self.player.mediaStatus() == QMediaPlayer.LoadedMedia:
                self.queueList.setCurrentIndex(self.position)
                self.player.play()
            elif self.player.mediaStatus() == QMediaPlayer.BufferedMedia:
                self.player.play()
        elif self.player.state() == QMediaPlayer.PlayingState:
            icon = QIcon.fromTheme("media-playback-start")
            self.player.pause()
        elif self.player.state() == QMediaPlayer.PausedState:
            self.player.play()

        self.parent.playBtn.setIcon(icon)

    def startPlay(self):
        data = self.queueData[0]
        self.queueList.setCurrentIndex(0)
        self.parent.curPCLabel.setText(data['pc_title'])
        self.parent.curTrackName.setText(data['title'])
        self.player.play()
        icon = QIcon.fromTheme("media-playback-pause")
        self.parent.playBtn.setIcon(icon)

    def stop(self):
        self.player.stop()
        icon = QIcon.fromTheme("media-playback-start")
        self.parent.playBtn.setIcon(icon)

    def setPosition(self, pos):
        self.player.setPosition(pos)

    def durationChanged(self, duration):
        total_time = '0:00:00'
        duration = self.player.duration()
        total_time = ms_to_time(duration)
        self.parent.timeSlider.setMaximum(duration)
        self.currentTrackDuration = duration
        self.parent.totalTimeLabel.setText(total_time)

    def qmp_mediaStatusChanged(self, status):
        icon = QIcon.fromTheme("media-playback-pause")
        if self.player.state() == QMediaPlayer.StoppedState:
            icon = QIcon.fromTheme("media-playback-start")
        elif self.player.state() == QMediaPlayer.PausedState:
            icon = QIcon.fromTheme("media-playback-start")

        self.parent.playBtn.setIcon(icon)

    def qmp_positionChanged(self, position, senderType=False):
        self.currentTime = position
        current_time = '0:00:00'

        if position != -1:
            current_time = ms_to_time(position)
            self.parent.timeLabel.setText(current_time)

        self.parent.timeSlider.blockSignals(True)
        self.parent.timeSlider.setValue(position)
        self.parent.timeSlider.blockSignals(False)

    def playlistPosChanged(self):
        pos = self.queueList.currentIndex()
        data = self.queueData[pos]
        self.parent.curPCLabel.setText(data['pc_title'])
        self.parent.curTrackName.setText(data['title'])
        windowTitle = '{0} - {1}'.format(data['pc_title'], data['title'])
        self.parent.setWindowTitle(windowTitle)
        if self.queueList.mediaCount() > 1:
            if pos < self.queueList.mediaCount() - 1:
                self.parent.queueNextBtn.setEnabled(True)
            else:
                self.parent.queueNextBtn.setEnabled(False)

            if pos > 0:
                self.parent.queuePrevBtn.setEnabled(True)
            else:
                self.parent.queuePrevBtn.setEnabled(False)

            if pos < self.queueList.mediaCount():
                prevPos = 0
                if self.position < pos:
                    prevPos = pos - 1
                else:
                    prevPos = pos + 1
                prevItem = self.parent.queueList.item(prevPos)
                prevWidget = self.parent.queueList.itemWidget(prevItem)
                if prevItem:
                    prevWidget.statusIcon.setPixmap(QPixmap())

        self.position = pos
        item = self.parent.queueList.item(pos)
        widget = self.parent.queueList.itemWidget(item)
        if widget:
            icon = QIcon.fromTheme("media-playback-start")
            widget.statusIcon.setPixmap(icon.pixmap(16, 16))

    def setVolume(self, volume):
        self.player.setVolume(volume)

    def rev10Secs(self):
        position = self.player.position()
        new_pos = position - 10000
        self.player.setPosition(new_pos)

    def for10Secs(self):
        position = self.player.position()
        new_pos = position + 10000
        self.player.setPosition(new_pos)

    def delete(self, position):
        """ Delete the track and her data from position"""
        self.queueData.pop(position)
        self.queueList.removeMedia(position)
        if (position == self.position):
            self.playlistPosChanged()
Beispiel #37
0
class Player(QWidget):
    audio_path = "audio"
    lyrics_path = "lyrics"
    timings_path = os.path.join("lyrics", "timing")
    settings_path = "settings.json"

    fullScreenChanged = pyqtSignal(bool)

    def __init__(self, parent=None):
        super(Player, self).__init__(parent)

        self.setWindowTitle("SongScreen")

        self.setFocusPolicy(Qt.StrongFocus)

        self.colorDialog = None
        self.trackInfo = ""
        self.statusInfo = ""
        self.duration = 0

        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)

        self.player.durationChanged.connect(self.durationChanged)
        self.player.positionChanged.connect(self.positionChanged)
        self.player.metaDataChanged.connect(self.metaDataChanged)
        # self.playlist.currentIndexChanged.connect(self.playlistPositionChanged)
        self.player.mediaStatusChanged.connect(self.statusChanged)
        self.player.bufferStatusChanged.connect(self.bufferingProgress)
        self.player.videoAvailableChanged.connect(self.videoAvailableChanged)
        self.player.error.connect(self.displayErrorMessage)

        # self.videoWidget = VideoWidget()
        # self.player.setVideoOutput(self.videoWidget)

        self.slider = MediaProgressWidget()  # QSlider(Qt.Horizontal)
        self.markers = []

        self.songtext_widget = SongTextWidget()
        self.songtext_widget.show()

        # self.playlistModel = PlaylistModel()
        # self.playlistModel.setPlaylist(self.playlist)
        #
        # self.playlistView = QListView()
        # self.playlistView.setModel(self.playlistModel)
        # self.playlistView.setCurrentIndex(
        #     self.playlistModel.index(self.playlist.currentIndex(), 0))
        #
        # self.playlistView.activated.connect(self.jump)

        self.slider.setRange(0, self.player.duration() / 1000)

        self.labelDuration = QLabel()
        self.slider.sliderMoved.connect(self.seek)

        # openButton = QPushButton("Open", clicked=self.open)

        controls = PlayerControlsWidget()
        controls.setState(self.player.state())
        controls.setVolume(self.player.volume())
        # controls.setMuted(controls.isMuted())

        controls.play.connect(self.player.play)
        controls.pause.connect(self.player.pause)
        controls.stop.connect(self.stop_clicked)
        # controls.stop.connect(self.videoWidget.update)
        # controls.next.connect(self.playlist.next)
        # controls.previous.connect(self.previousClicked)
        controls.changeVolume.connect(self.player.setVolume)
        # controls.changeMuting.connect(self.player.setMuted)
        # controls.changeRate.connect(self.player.setPlaybackRate)

        self.player.stateChanged.connect(controls.setState)
        self.player.stateChanged.connect(self.setState)
        self.player.volumeChanged.connect(controls.setVolume)
        # self.player.mutedChanged.connect(controls.setMuted)

        # self.fullScreenButton = QPushButton("FullScreen")
        # self.fullScreenButton.setCheckable(True)
        #
        # self.colorButton = QPushButton("Color Options...")
        # self.colorButton.setEnabled(False)
        # self.colorButton.clicked.connect(self.showColorDialog)

        displayLayout = QHBoxLayout()
        # displayLayout.addWidget(self.videoWidget, 2)
        # displayLayout.addWidget(self.songtext_widget)
        # displayLayout.addWidget(self.playlistView)

        self.song_select_widget = SongSelectWidget()
        self.song_select_widget.song_selected.connect(self.load_song)

        self.screen_select_widget = ScreenSelectWidget()
        self.screen_select_widget.screen_selected.connect(self.display_lyrics_on_screen)
        self.screen_select_widget.active_screen = QApplication.desktop().screenNumber(self.songtext_widget)

        self.settings_button = QPushButton()
        self.settings_button.setText(self.tr("Settings..."))
        self.settings_button.clicked.connect(self.show_settings)

        sidebarLayout = QVBoxLayout()
        sidebarLayout.setContentsMargins(10, 1, 0, 1);

        sidebarLayout.addWidget(self.settings_button)
        sidebarLayout.addStretch(1);
        sidebarLayout.addWidget(self.screen_select_widget)

        displayLayout.addWidget(self.song_select_widget)
        displayLayout.addLayout(sidebarLayout)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        # controlLayout.addWidget(openButton)
        # controlLayout.addStretch(1)
        controlLayout.addWidget(controls)
        controlLayout.addStretch(1)
        controlLayout.addWidget(self.labelDuration)
        # controlLayout.addWidget(self.fullScreenButton)
        # controlLayout.addWidget(self.colorButton)

        layout = QVBoxLayout()
        layout.addLayout(displayLayout)
        hLayout = QHBoxLayout()
        hLayout.addWidget(self.slider)
        # hLayout.addWidget(self.labelDuration)
        layout.addLayout(hLayout)
        layout.addLayout(controlLayout)

        self.setLayout(layout)

        if not self.player.isAvailable():
            QMessageBox.warning(self, "Service not available",
                                "The QMediaPlayer object does not have a valid service.\n"
                                "Please check the media service plugins are installed.")

            controls.setEnabled(False)
            self.playlistView.setEnabled(False)
            # openButton.setEnabled(False)
            self.colorButton.setEnabled(False)
            self.fullScreenButton.setEnabled(False)

        self.metaDataChanged()

        self._loading_audio = False
        self._finished_song = False
        self._lyrics_fading = False

        self._song_number = -1

        self.settings = {
            'font_size': 40,
            'line_increment': 2,
            'lyrics_language': '',
        }
        self._load_settings()

        self.settings_widget = SettingsWidget(self.settings, self.lyrics_path)
        self.settings_widget.font_size_changed.connect(self.songtext_widget.set_font_size)
        self.settings_widget.line_increment_changed.connect(self.songtext_widget.set_line_increment)
        self.settings_widget.language_changed.connect(self._language_changed)

        self.song_select_widget.reset(self.available_song_numbers)

    @property
    def lyrics_language_path(self):
        path = QStandardPaths.locate(QStandardPaths.AppDataLocation, self.lyrics_path, QStandardPaths.LocateDirectory)
        return os.path.join(path, self.settings['lyrics_language'])

    @property
    def available_song_numbers(self):
        audios = set(
            [int(os.path.splitext(filename)[0]) for filename in os.listdir(self.audio_path) if filename[0] != '.'])
        try:
            lyrics = set(
                [int(os.path.splitext(filename)[0])
                 for filename in os.listdir(self.lyrics_language_path)
                 if filename[0] != '.']
            )
        except (ValueError, FileNotFoundError):
            lyrics = set()

        return sorted(list(audios.intersection(lyrics)))

    def show_settings(self):
        self.settings_widget.hide()
        self.settings_widget.show()

    def display_lyrics_on_screen(self, screen_number):
        desktop = QApplication.desktop()

        if screen_number >= desktop.screenCount():
            screen_number = desktop.screenNumber(self)

        rect = desktop.availableGeometry(screen_number)

        for _ in range(3):
            if screen_number != desktop.screenNumber(self):
                self.songtext_widget.setWindowFlags(Qt.FramelessWindowHint)
                self.songtext_widget.hide()
                self.songtext_widget.move(rect.x(), rect.y())
                self.songtext_widget.resize(rect.width(), rect.height())
                self.songtext_widget.showFullScreen()
            else:
                self.songtext_widget.setWindowFlags(Qt.WindowTitleHint)
                self.songtext_widget.hide()
                self.songtext_widget.move(rect.x(), rect.y())
                self.songtext_widget.resize(self.songtext_widget.minimumSize())
                self.songtext_widget.show()

        self.screen_select_widget.active_screen = screen_number

        self.activateWindow()

    def load_song(self, song_number):
        if self._song_number == song_number:
            self.seek(0)
        else:
            if self._song_number > 0:
                self._save_timings()

            self._song_number = song_number
            self.slider.dirty = False
            self._load_audio()
            self._load_lyrics()

            # self.player.play()

    def _load_audio(self):
        filename = os.path.join(self.audio_path, "{:03}.mp3".format(self._song_number))
        self.playlist.clear()
        fileInfo = QFileInfo(filename)
        if fileInfo.exists():
            url = QUrl.fromLocalFile(fileInfo.absoluteFilePath())
            if fileInfo.suffix().lower() == 'm3u':
                self.playlist.load(url)
            else:
                self.playlist.addMedia(QMediaContent(url))
                self._loading_audio = True

            self.player.play()

    def _load_lyrics(self):
        with open(os.path.join(self.lyrics_language_path, "{}.json".format(self._song_number)), 'r') as f:
            song_markers = json.load(f)

            self.markers = []

            for m in song_markers['markers']:
                marker = MediaMarker(self.slider, m['name'])
                marker.text = m['text']
                marker.progress = 0.0
                self.markers.append(marker)

            self.songtext_widget.title = "{}  {}".format(self._song_number, song_markers['title'])
            self.songtext_widget.markers = self.markers
            self.songtext_widget.fade_in()

        try:
            with open(os.path.join(self.timings_path, "{}.json".format(self._song_number)), 'r') as f:
                timings = json.load(f)
                for m, t in zip(self.markers, timings):
                    m.progress = t
        except FileNotFoundError:
            pass

        self.slider.markers = self.markers

    def _language_changed(self, _):
        available_song_numbers = self.available_song_numbers
        self.song_select_widget.reset(available_song_numbers)
        if self._song_number in available_song_numbers:
            self._load_lyrics()

    # def open(self):
    #     fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files")
    #     self.addToPlaylist(fileNames)
    #
    # def addToPlaylist(self, fileNames):
    #     for name in fileNames:
    #         fileInfo = QFileInfo(name)
    #         if fileInfo.exists():
    #             url = QUrl.fromLocalFile(fileInfo.absoluteFilePath())
    #             if fileInfo.suffix().lower() == 'm3u':
    #                 self.playlist.load(url)
    #             else:
    #                 self.playlist.addMedia(QMediaContent(url))
    #         else:
    #             url = QUrl(name)
    #             if url.isValid():
    #                 self.playlist.addMedia(QMediaContent(url))

    def durationChanged(self, duration):
        duration /= 1000

        self.duration = duration
        self.slider.setMaximum(duration)

        if self._loading_audio:
            self._loading_audio = False

            line_total = 0
            for marker in self.markers:
                line_total += marker.linecount - 1

            silence_ratio = 5.0 / self.duration
            offset = 1.8 / line_total

            linecount = 0
            for marker in self.markers:
                if marker.progress == 0.0:
                    marker.progress = offset + (1 - offset) * (1 - silence_ratio) * linecount / line_total
                linecount += marker.linecount - 1

            self.player.pause()

    @property
    def _should_fade_out(self):
        return self.player.position() / 1000 >= self.duration - 5

    def positionChanged(self, progress):
        progress /= 1000

        if not self.slider.isSliderDown():
            self.slider.setValue(progress)

        self.updateDurationInfo(progress)

        if self.duration > 0:
            # if self.player.state() == QMediaPlayer.PlayingState:
            self.songtext_widget.progress = progress / self.duration

            if self._should_fade_out:
                self._fade_out_lyrics()

    def _fade_out_lyrics(self):
        if not self._lyrics_fading:
            self._lyrics_fading = True
            self.songtext_widget.fade_out()

    def metaDataChanged(self):
        if self.player.isMetaDataAvailable():
            self.setTrackInfo("%s - %s" % (
                self.player.metaData(QMediaMetaData.AlbumArtist),
                self.player.metaData(QMediaMetaData.Title)))

    def previousClicked(self):
        # Go to the previous track if we are within the first 5 seconds of
        # playback.  Otherwise, seek to the beginning.
        if self.player.position() <= 5000:
            self.playlist.previous()
        else:
            self.player.setPosition(0)

    def jump(self, index):
        if index.isValid():
            self.playlist.setCurrentIndex(index.row())
            self.player.play()

    def seek(self, seconds):
        self.player.setPosition(seconds * 1000)

    def setState(self, status):

        if status == QMediaPlayer.StoppedState:
            self._finished_song = True

        elif status == QMediaPlayer.PlayingState:
            if self._finished_song or (self._lyrics_fading and not self._should_fade_out):
                self._finished_song = False
                self._lyrics_fading = False
                self.songtext_widget.fade_in()

    def stop_clicked(self):
        self.player.stop()
        self._fade_out_lyrics()

    def statusChanged(self, status):
        self.handleCursor(status)

        if status == QMediaPlayer.LoadingMedia:
            self.setStatusInfo("Loading...")
        elif status == QMediaPlayer.StalledMedia:
            self.setStatusInfo("Media Stalled")
        elif status == QMediaPlayer.EndOfMedia:
            QApplication.alert(self)
        elif status == QMediaPlayer.InvalidMedia:
            self.displayErrorMessage()
        else:
            self.setStatusInfo("")

    def handleCursor(self, status):
        if status in (QMediaPlayer.LoadingMedia, QMediaPlayer.BufferingMedia, QMediaPlayer.StalledMedia):
            self.setCursor(Qt.BusyCursor)
        else:
            self.unsetCursor()

    def bufferingProgress(self, progress):
        self.setStatusInfo("Buffering %d%" % progress)

    def videoAvailableChanged(self, available):
        if available:
            self.fullScreenButton.clicked.connect(
                self.videoWidget.setFullScreen)
            self.videoWidget.fullScreenChanged.connect(
                self.fullScreenButton.setChecked)

            if self.fullScreenButton.isChecked():
                self.videoWidget.setFullScreen(True)
        else:
            self.fullScreenButton.clicked.disconnect(
                self.videoWidget.setFullScreen)
            self.videoWidget.fullScreenChanged.disconnect(
                self.fullScreenButton.setChecked)

            self.videoWidget.setFullScreen(False)

        self.colorButton.setEnabled(available)

    def setTrackInfo(self, info):
        self.trackInfo = info

        # if self.statusInfo != "":
        #     self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo))
        # else:
        #     self.setWindowTitle(self.trackInfo)

    def setStatusInfo(self, info):
        self.statusInfo = info

        # if self.statusInfo != "":
        #     self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo))
        # else:
        #     self.setWindowTitle(self.trackInfo)

    def displayErrorMessage(self):
        self.setStatusInfo(self.player.errorString())

    def updateDurationInfo(self, currentInfo):
        duration = self.duration
        if currentInfo or duration:
            currentTime = QTime((currentInfo / 3600) % 60, (currentInfo / 60) % 60,
                                currentInfo % 60, (currentInfo * 1000) % 1000)
            totalTime = QTime((duration / 3600) % 60, (duration / 60) % 60,
                              duration % 60, (duration * 1000) % 1000);

            format = 'hh:mm:ss' if duration > 3600 else 'mm:ss'
            tStr = currentTime.toString(format) + " / " + totalTime.toString(format)
        else:
            tStr = ""

        self.labelDuration.setText(tStr)

    def showColorDialog(self):
        if self.colorDialog is None:
            brightnessSlider = QSlider(Qt.Horizontal)
            brightnessSlider.setRange(-100, 100)
            brightnessSlider.setValue(self.videoWidget.brightness())
            brightnessSlider.sliderMoved.connect(
                self.videoWidget.setBrightness)
            self.videoWidget.brightnessChanged.connect(
                brightnessSlider.setValue)

            contrastSlider = QSlider(Qt.Horizontal)
            contrastSlider.setRange(-100, 100)
            contrastSlider.setValue(self.videoWidget.contrast())
            contrastSlider.sliderMoved.connect(self.videoWidget.setContrast)
            self.videoWidget.contrastChanged.connect(contrastSlider.setValue)

            hueSlider = QSlider(Qt.Horizontal)
            hueSlider.setRange(-100, 100)
            hueSlider.setValue(self.videoWidget.hue())
            hueSlider.sliderMoved.connect(self.videoWidget.setHue)
            self.videoWidget.hueChanged.connect(hueSlider.setValue)

            saturationSlider = QSlider(Qt.Horizontal)
            saturationSlider.setRange(-100, 100)
            saturationSlider.setValue(self.videoWidget.saturation())
            saturationSlider.sliderMoved.connect(
                self.videoWidget.setSaturation)
            self.videoWidget.saturationChanged.connect(
                saturationSlider.setValue)

            layout = QFormLayout()
            layout.addRow("Brightness", brightnessSlider)
            layout.addRow("Contrast", contrastSlider)
            layout.addRow("Hue", hueSlider)
            layout.addRow("Saturation", saturationSlider)

            button = QPushButton("Close")
            layout.addRow(button)

            self.colorDialog = QDialog(self)
            self.colorDialog.setWindowTitle("Color Options")
            self.colorDialog.setLayout(layout)

            button.clicked.connect(self.colorDialog.close)

        self.colorDialog.show()

    def closeEvent(self, close_event):
        self._save_timings()
        self._save_settings()
        self.songtext_widget.close()
        self.settings_widget.close()

    def keyPressEvent(self, key_event):
        if key_event.key() == Qt.Key_Space:
            key_event.accept()
            if self.player.state() == QMediaPlayer.PlayingState:
                self.player.pause()
            elif self.player.state() in [QMediaPlayer.PausedState, QMediaPlayer.StoppedState]:
                self.player.play()
        elif key_event.key() == Qt.Key_M:
            key_event.accept()
            self.slider.set_closest_marker_to_current_progress()

    def _save_timings(self):
        if self.slider.dirty:
            with open(os.path.join(self.timings_path, "{}.json".format(self._song_number)), 'w') as f:
                json.dump([marker.progress for marker in self.markers], f, indent=2)

    def _save_settings(self):
        # TODO : refactor and use QSettings directly

        # with open(self.settings_path, 'w') as f:
        self.settings.update({
            'lyrics_screen': QApplication.desktop().screenNumber(self.songtext_widget),
            'control_window_position': self.pos(),
        })

        # json.dump(self.settings, f, indent=2)

        settings = QSettings("Maccesch", "SongScreen")

        for key, value in self.settings.items():
            settings.setValue(key, value)

    def _load_settings(self):
        # try:
        #     with open(self.settings_path, 'r') as f:
        #         settings = json.load(f)
        settings = QSettings("Maccesch", "SongScreen")

        if settings.contains('lyrics_screen'):
            self.display_lyrics_on_screen(settings.value('lyrics_screen'))

        if settings.contains('control_window_position'):
            self.move(settings.value('control_window_position'))

        for key in settings.allKeys():
            self.settings[key] = settings.value(key)

        # self.settings.update(settings)

        self.songtext_widget.set_font_size(self.settings['font_size'])
        self.songtext_widget.set_line_increment(self.settings['line_increment'])

        # except (FileNotFoundError, ValueError):
        #     pass

        if not os.path.exists(self.lyrics_language_path) or not self.settings['lyrics_language']:
            languages = list(
                filter(lambda p: os.path.isdir(os.path.join(self.lyrics_path, p)) and p != "timings",
                       os.listdir(self.lyrics_path))
            )
            self.settings['lyrics_language'] = languages[0] if languages else ""
class MyWin(QtWidgets.QMainWindow):

    lbs = []
    rbs = [[''] * 10] * 15  # emply list 15x10
    bgrs = []
    labels = []
    variants = []
    correct = []
    value = []
    tp = []
    picName = []
    lblPic = []
    logStr = ''
    triggeredNum = 0
    minNum = 0
    name1 = ''
    group1 = ''
    timeRes = 0
    timesListening = 4

    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        while self.name1 == '' or self.group1 == '':
            dialog = StartDialog(self)
            if dialog.exec_():
                self.name1 = dialog.lineEdit.text()
                self.group1 = dialog.lineEdit_2.text()

        self.duration = 0
        self.playerState = QMediaPlayer.StoppedState
        self.timerAud = QtCore.QTimer(self)
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)

        # frame with buttons play and stop, and duration label
        self.frame = QtWidgets.QFrame(self.ui.scrollAreaWidgetContents)
        self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.frame)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton = QtWidgets.QPushButton(self.frame)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout.addWidget(self.pushButton)
        self.pushButton_3 = QtWidgets.QPushButton(self.frame)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout.addWidget(self.pushButton_3)
        self.labelDuration = QtWidgets.QLabel(self.frame)
        self.labelDuration.setText('0')
        self.horizontalLayout.addWidget(self.labelDuration)

        # creating timer
        self.timer = QtCore.QTimer(self)
        # xml handling (read & mix)
        self.mixXml()
        # read to DOM
        self.readToDom()
        # assigning layout to the scrollarea
        self.verticalLayout = QtWidgets.QVBoxLayout(
            self.ui.scrollAreaWidgetContents)
        self.verticalLayout.setObjectName("verticalLayout")
        # adding title
        self.trTitle = QtWidgets.QLabel(self.ui.scrollAreaWidgetContents)
        self.trTitle.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
                                  | QtCore.Qt.AlignTop)
        self.trTitle.setText('')
        # adding standart widgets for listening
        self.verticalLayout.addWidget(self.trTitle)
        self.lblAud = QtWidgets.QLabel(self.ui.scrollAreaWidgetContents)
        self.lblAud.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.AlignLeft
                                 | QtCore.Qt.AlignTop)
        self.lblAud.setText('')
        self.horizontalSlider = QtWidgets.QSlider(
            self.ui.scrollAreaWidgetContents)
        self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalSlider.setObjectName("horizontalSlider")

        # adding frame
        self.verticalLayout.addWidget(self.lblAud)
        self.verticalLayout.addWidget(self.horizontalSlider)
        self.verticalLayout.addWidget(self.frame)

        self.pushButton.setIcon(self.style().standardIcon(
            QtWidgets.QStyle.SP_MediaPlay))
        self.pushButton_3.setIcon(self.style().standardIcon(
            QtWidgets.QStyle.SP_MediaStop))
        self.pushButton_3.setEnabled(False)

        # adding widgets to the scrollarea
        self.addWidgetsToInterface()
        self.timer.timeout.connect(lambda: self.updater(self.timeSeconds))
        # starting timer
        self.timer.start(1000)

        self.player.durationChanged.connect(self.durationChanged1)
        self.player.positionChanged.connect(self.positionChanged1)
        self.player.stateChanged.connect(self.setState)

        self.horizontalSlider.setRange(0, self.player.duration() / 1000)

        self.pushButton.clicked.connect(self.play1)
        self.pushButton_3.clicked.connect(self.stop1)

        self.horizontalSlider.sliderMoved.connect(self.changePosition)

        self.ui.pushButton.clicked.connect(self.finish)

    def open1(self, filename):
        self.audiofile = filename
        fileInfo = QtCore.QFileInfo(self.audiofile)
        url = QtCore.QUrl.fromLocalFile(fileInfo.absoluteFilePath())
        self.playlist.addMedia(QMediaContent(url))
        self.pushButton.setEnabled(True)

    def play1(self):
        if self.playerState in (QMediaPlayer.StoppedState,
                                QMediaPlayer.PausedState):
            self.player.play()
        elif self.playerState == QMediaPlayer.PlayingState:
            self.player.pause()

    def stop1(self):
        self.player.stop()

    def positionChanged1(self, progress):
        progress = progress / 1000
        if not self.horizontalSlider.isSliderDown():
            self.horizontalSlider.setValue(progress)
        self.updateDurationInfo(progress)

    def durationChanged1(self, duration):
        duration = duration / 1000
        self.duration = duration
        self.horizontalSlider.setMaximum(duration)

    def updateDurationInfo(self, currentInfo):
        duration = self.duration
        if currentInfo or duration:
            currentTime = QtCore.QTime(
                (currentInfo / 3600) % 60, (currentInfo / 60) % 60,
                currentInfo % 60, (currentInfo * 1000) % 1000)
            totalTime = QtCore.QTime((duration / 3600) % 60,
                                     (duration / 60) % 60, duration % 60,
                                     (duration * 1000) % 1000)
            format1 = 'hh:mm:ss' if duration > 3600 else 'mm:ss'
            tStr = currentTime.toString(format1) + " / " + totalTime.toString(
                format1)
        else:
            tStr = ''
        if (self.timesListening - 1) < 0:
            self.labelDuration.setText(tStr +
                                       ' -осталось количество прослушиваний ' +
                                       '0')
        else:
            self.labelDuration.setText(tStr +
                                       ' -осталось количество прослушиваний ' +
                                       str(self.timesListening - 1))

    def setState(self, state):
        if state != self.playerState:
            self.playerState = state
            if state == QMediaPlayer.StoppedState:
                self.timesListening -= 1
                if self.timesListening <= 0:
                    self.pushButton.clicked.connect(self.stop1)
                self.horizontalSlider.setEnabled(False)
                self.pushButton_3.setEnabled(False)
                self.pushButton.setIcon(self.style().standardIcon(
                    QtWidgets.QStyle.SP_MediaPlay))
            elif state == QMediaPlayer.PlayingState:
                self.horizontalSlider.setEnabled(True)
                self.pushButton_3.setEnabled(True)
                self.pushButton.setIcon(self.style().standardIcon(
                    QtWidgets.QStyle.SP_MediaPause))
            elif state == QMediaPlayer.PausedState:
                self.horizontalSlider.setEnabled(False)
                self.pushButton_3.setEnabled(True)
                self.pushButton.setIcon(self.style().standardIcon(
                    QtWidgets.QStyle.SP_MediaPlay))

    def changePosition(self, seconds):
        if self.playerState == QMediaPlayer.PausedState:
            pass
        elif self.playerState == QMediaPlayer.PlayingState:
            self.player.setPosition(seconds * 1000)

    def finish(self):
        self.timeRes = self.timeSeconds
        self.timeSeconds = 0

    def mixXml(self):
        # read xml and mix the lines
        self.linesMixed = []
        self.r = open("db6.xml", 'r', encoding='utf-8')
        self.fileRead = self.r.readlines()
        for line in range(2, len(self.fileRead) - 1):
            self.linesMixed.append(self.fileRead[line])
        random.shuffle(self.linesMixed)
        self.r.close()

        # write temporary xml with new mixed lines
        self.w = open("temp.xml", 'w', encoding='utf-8')
        self.w.write('''<?xml version="1.0" encoding="utf-8"?>\n<content>\n''')
        for line in self.linesMixed:
            self.w.write('%s' % line)
        self.w.write('</content>')
        self.w.close()

    def readToDom(self):
        # read to DOM
        self.dom = xml.dom.minidom.parse('temp.xml')
        self.collection = self.dom.documentElement
        # reading timeout to a variable
        self.timeSeconds = int(
            self.collection.getElementsByTagName("time")[0].childNodes[0].data)
        # reading title
        self.title = self.collection.getElementsByTagName(
            "ttl")[0].childNodes[0].data
        self.questAudio = self.collection.getElementsByTagName(
            "aud")[0].childNodes[0].data
        aud = self.collection.getElementsByTagName("aud")[0]
        audFile = aud.getAttribute('src')
        self.open1(audFile)
        self.timeConstant = self.timeSeconds
        self.linesArr = self.collection.getElementsByTagName("q")
        for line in range(0, len(self.linesArr)):
            # label's text
            self.labels.append(self.linesArr[line].childNodes[0].data)
            # variants' text
            self.variants.append(
                self.linesArr[line].getAttribute('ans').split('**?**'))
            # correct answer
            self.correct.append(self.linesArr[line].getAttribute('cor'))
            # value
            self.value.append(int(self.linesArr[line].getAttribute('pnt')))
            # reading type
            self.tp.append(self.linesArr[line].getAttribute('type'))
            # adding picture name if any
            if self.linesArr[line].hasAttribute('pic'):
                self.picName.append(self.linesArr[line].getAttribute('pic'))
            else:
                self.picName.append('empty')
        # Mix variants
        for variant in self.variants:
            random.shuffle(variant)
        # Deleting temporary file
        os.remove('temp.xml')

    def addWidgetsToInterface(self):
        # adding widgets to the scrollarea
        self.trTitle.setText("Тренажер %s" % self.title)
        self.lblAud.setText("<b>%s</b>" % self.questAudio)
        for line in range(0, len(self.labels)):
            self.lbs.append(QtWidgets.QLabel(self.ui.scrollAreaWidgetContents))
            self.lbs[line].setAlignment(QtCore.Qt.AlignLeading
                                        | QtCore.Qt.AlignLeft
                                        | QtCore.Qt.AlignTop)
            self.lbs[line].setText('<b>%s</b>' % self.labels[line])
            self.verticalLayout.addWidget(self.lbs[line])
            # adding picture
            if self.picName[line] != 'empty':
                self.lblPic.append(
                    QtWidgets.QLabel(self.ui.scrollAreaWidgetContents))
                self.lblPic[line].setAlignment(QtCore.Qt.AlignLeading
                                               | QtCore.Qt.AlignLeft
                                               | QtCore.Qt.AlignTop)
                self.lblPic[line].setPixmap(
                    QtGui.QPixmap(os.getcwd() + "/" + self.picName[line]))
                self.verticalLayout.addWidget(self.lblPic[line])
            else:
                self.lblPic.append(
                    QtWidgets.QLabel(self.ui.scrollAreaWidgetContents))
            # adding button group
            self.bgrs.append(QtWidgets.QButtonGroup(self.ui.centralwidget))
            if self.tp[line] == 'chb':
                self.bgrs[line].setExclusive(False)
                self.correct[line] = self.correct[line].split('**?**')
            # click counter
            self.bgrs[line].buttonClicked.connect(self.increaseNum)
            for v in range(0, len(self.variants[line])):
                # check br/chb
                if self.tp[line] == 'rb':
                    self.rbs[line][v] = QtWidgets.QRadioButton(
                        self.ui.scrollAreaWidgetContents)
                elif self.tp[line] == 'chb':
                    self.rbs[line][v] = QtWidgets.QCheckBox(
                        self.ui.scrollAreaWidgetContents)
                self.bgrs[line].addButton(self.rbs[line][v])
                self.rbs[line][v].setText(self.variants[line][v])
                self.verticalLayout.addWidget(self.rbs[line][v])

    def increaseNum(self):
        self.triggeredNum += 1

    def check(self):
        counter = 0
        for group in range(0, len(self.bgrs)):
            # adding questions
            self.logStr += self.labels[group] + '\n'
            self.logStr += 'Сложность: %d\n' % self.value[group]
            # check rb/chb
            if self.tp[group] == 'rb':
                self.minNum += 1
                correctThis = '--'
                for rb in self.bgrs[group].buttons():
                    # adding variants
                    self.logStr += '\t' + rb.text() + '\n'
                    if rb.isChecked():
                        if rb.text() == self.correct[group]:
                            correctThis = rb.text()
                            counter += self.value[group]
            elif self.tp[group] == 'chb':
                if self.correct[group][0] != 'none':
                    self.minNum += len(self.correct[group])
                correctThis = []
                chbCor = []
                for rb in self.bgrs[group].buttons():
                    # adding variants
                    self.logStr += '\t' + rb.text() + '\n'
                    if rb.isChecked():
                        # marked checkboxes
                        chbCor.append(rb.text())
                if len(chbCor) == 0:
                    chbCor.append('none')
                chbCor.sort()
                self.correct[group].sort()
                if self.correct[group] == chbCor:
                    counter += self.value[group]
                correctThis = chbCor

            self.logStr += 'Правильный ответ: %s' % self.listToString(
                self.correct[group]) + '\n'
            self.logStr += 'Ответ пользователя: %s' % self.listToString(
                correctThis) + '\n'
            if self.listToString(
                    self.correct[group]) == self.listToString(correctThis):
                self.logStr += 'TRUE\n'
            else:
                self.logStr += 'FALSE\n'
            self.logStr += '\n'
        # And this is the result! Rounded to 2 decimal points
        self.result = float(counter / sum(self.value) * 100)
        message = "Your result is " + "%.2f" % self.result + "%"
        self.ui.statusbar.setStyleSheet('color: navy; font-weight: bold;')
        self.ui.statusbar.showMessage(message)
        # creating log file
        self.log()

    def listToString(self, getlist):
        if type(getlist).__name__ == 'list':
            string = ''
            for i in getlist:
                string += i + '; '
            string = string[:-2] + '.'
            return string
        else:
            return getlist

    def updater(self, val):
        val = self.timeSeconds
        if val == 0:
            self.timer.stop()
            self.check()
            self.ui.scrollArea.setEnabled(False)
            self.ui.pushButton.setEnabled(False)
        self.ui.label.setText(self.intToTime(val))
        self.timeSeconds -= 1

    def intToTime(self, num):
        h = 0
        m = 0
        if num >= 3600:
            h = num // 3600
            num = num % 3600
        if num >= 60:
            m = num // 60
            num = num % 60
        s = num
        str1 = "%d." % h
        if m < 10:
            str1 += "0%d:" % m
        else:
            str1 += "%d:" % m
        if s < 10:
            str1 += "0%d" % s
        else:
            str1 += "%d" % s
        return str1  # returns time as a string

    def log(self):
        logFileName = self.name1 + '_' + self.group1 + '_%.2f' % self.result + '_' + str(
            self.timeConstant - self.timeRes) + '_%.2f' % (
                self.triggeredNum / self.minNum * 100) + '_' + str(
                    int(round(time.time() * 1000))) + '.txt'
        file = open(logFileName, 'w', encoding='utf-8')
        file.write("Тренажер: %s\n" % self.title)
        file.write("Имя: %s\nГруппа: %s\n" % (self.name1, self.group1))
        file.write("Дата и время записи: ")
        file.write(time.strftime("%Y-%m-%d %H:%M:%S"))
        file.write('\n\n')
        file.write(self.logStr)
        file.write('\n')
        file.write("Результат: %.2f" % self.result + " %\n")
        file.write('Выполнено за %d с\n' % (self.timeConstant - self.timeRes))
        # Nubmer of iteractions in percent relative to minimal number of interactions.
        # Minimal number of iteractions equals the quantity of radio buttons
        # multiplied by the quantity of correct variants in questions with check boxes
        # see line 140 and 150-151.
        file.write('Коэффициент интеракций: %.2f' %
                   (self.triggeredNum / self.minNum * 100) + ' %')
        # makes log file read only
        os.chmod(os.path.abspath(logFileName), stat.S_IREAD)
        file.close()
        self.triggeredNum = 0
        self.logStr = ''
Beispiel #39
0
class Demo(QWidget):
    def __init__(self):
        super(Demo, self).__init__()

        self.time_label = QLabel(self)
        self.volume_slider = QSlider(self)
        self.progress_slider = QSlider(self)
        self.sound_btn = QPushButton(self)
        self.previous_btn = QPushButton(self)
        self.play_pause_btn = QPushButton(self)
        self.next_btn = QPushButton(self)
        self.mode_btn = QPushButton(self)
        self.list_btn = QPushButton(self)
        self.list_widget = QListWidget(self)

        self.h1_layout = QHBoxLayout()
        self.h2_layout = QHBoxLayout()
        self.all_v_layout = QVBoxLayout()

        self.playlist = QMediaPlaylist(self)        
        self.player = QMediaPlayer(self)

        self.widget_init()
        self.layout_init()
        self.signal_init()

    def widget_init(self):
        self.time_label.setText('--/--')
        self.volume_slider.setRange(0, 100)
        self.volume_slider.setValue(100)
        self.volume_slider.setOrientation(Qt.Horizontal)
        self.progress_slider.setEnabled(False)
        self.progress_slider.setOrientation(Qt.Horizontal)
        self.sound_btn.setIcon(QIcon('images/sound_on.png'))
        self.previous_btn.setIcon(QIcon('images/previous.png'))
        self.play_pause_btn.setIcon(QIcon('images/play.png'))
        self.next_btn.setIcon(QIcon('images/next.png'))
        self.mode_btn.setIcon(QIcon('images/list_loop.png'))
        self.list_btn.setIcon(QIcon('images/show.png'))

        self.player.setPlaylist(self.playlist)
        self.media_list = ['/Users/louis/Downloads/music1.mp3',
                           '/Users/louis/Downloads/music2.mp4',
                           '/Users/louis/Downloads/music3.mp3']
        for m in self.media_list:
            self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(m)))
        self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)

        self.list_widget.addItems([m.split('/')[-1] for m in self.media_list])

    def layout_init(self):
        self.h1_layout.addWidget(self.progress_slider)
        self.h1_layout.addWidget(self.time_label)
        self.h2_layout.addWidget(self.volume_slider)
        self.h2_layout.addWidget(self.sound_btn)
        self.h2_layout.addWidget(self.previous_btn)
        self.h2_layout.addWidget(self.play_pause_btn)
        self.h2_layout.addWidget(self.next_btn)
        self.h2_layout.addWidget(self.mode_btn)
        self.h2_layout.addWidget(self.list_btn)

        self.all_v_layout.addLayout(self.h1_layout)
        self.all_v_layout.addLayout(self.h2_layout)
        self.all_v_layout.addWidget(self.list_widget)
        self.all_v_layout.setSizeConstraint(QVBoxLayout.SetFixedSize)

        self.setLayout(self.all_v_layout)

    def signal_init(self):
        self.sound_btn.clicked.connect(lambda: self.btn_func(self.sound_btn))
        self.previous_btn.clicked.connect(lambda: self.btn_func(self.previous_btn))
        self.play_pause_btn.clicked.connect(lambda: self.btn_func(self.play_pause_btn))
        self.next_btn.clicked.connect(lambda: self.btn_func(self.next_btn))
        self.mode_btn.clicked.connect(lambda: self.btn_func(self.mode_btn))
        self.list_btn.clicked.connect(lambda: self.btn_func(self.list_btn))
        self.volume_slider.valueChanged.connect(self.volume_slider_func)
        self.list_widget.doubleClicked.connect(self.list_play_func)
        self.player.durationChanged.connect(self.get_duration_func)
        self.player.positionChanged.connect(self.get_position_func)
        self.progress_slider.sliderMoved.connect(self.update_position_func)

    def btn_func(self, btn):
        if btn == self.sound_btn:              
            if self.player.isMuted():
                self.player.setMuted(False)
                self.sound_btn.setIcon(QIcon('images/sound_on'))
            else:
                self.player.setMuted(True)
                self.sound_btn.setIcon(QIcon('images/sound_off'))

        elif btn == self.previous_btn:          
            if self.playlist.currentIndex() == 0:
                self.playlist.setCurrentIndex(self.playlist.mediaCount() - 1)
            else:
                self.playlist.previous()

        elif btn == self.play_pause_btn:      
            if self.player.state() == 1:
                self.player.pause()
                self.play_pause_btn.setIcon(QIcon('images/play.png'))
            else:
                self.player.play()
                self.play_pause_btn.setIcon(QIcon('images/pause.png'))

        elif btn == self.next_btn:              
            if self.playlist.currentIndex() == self.playlist.mediaCount() - 1:
                self.playlist.setCurrentIndex(0)
            else:
                self.playlist.next()

        elif btn == self.mode_btn:             
            if self.playlist.playbackMode() == 2:
                self.playlist.setPlaybackMode(QMediaPlaylist.Loop)
                self.mode_btn.setIcon(QIcon('images/item_loop.png'))

            elif self.playlist.playbackMode() == 3:
                self.playlist.setPlaybackMode(QMediaPlaylist.Random)
                self.mode_btn.setIcon(QIcon('images/random.png'))

            elif self.playlist.playbackMode() == 4:
                self.playlist.setPlaybackMode(QMediaPlaylist.Sequential)
                self.mode_btn.setIcon(QIcon('images/list_loop.png'))

        elif btn == self.list_btn:             
            if self.list_widget.isHidden():
                self.list_widget.show()
                self.list_btn.setIcon(QIcon('images/show.png'))
            else:
                self.list_widget.hide()
                self.list_btn.setIcon(QIcon('images/hide.png'))

    def volume_slider_func(self, value):
        self.player.setVolume(value)
        if value == 0:
            self.sound_btn.setIcon(QIcon('images/sound_off.png'))
        else:
            self.sound_btn.setIcon(QIcon('images/sound_on.png'))

    def list_play_func(self):
        self.playlist.setCurrentIndex(self.list_widget.currentRow())
        self.player.play()
        self.play_pause_btn.setIcon(QIcon('images/pause.png'))

    def get_duration_func(self, d):
        self.progress_slider.setRange(0, d)
        self.progress_slider.setEnabled(True)
        self.get_time_func(d)

    def get_time_func(self, d):
        seconds = int(d / 1000)
        minutes = int(seconds / 60)
        seconds -= minutes * 60
        if minutes == 0 and seconds == 0:
            self.time_label.setText('--/--')
            self.play_pause_btn.setIcon(QIcon('images/play.png'))
        else:
            self.time_label.setText('{}:{}'.format(minutes, seconds))

    def get_position_func(self, p):
        self.progress_slider.setValue(p)

    def update_position_func(self, v):
        self.player.setPosition(v)
        d = self.progress_slider.maximum() - v
        self.get_time_func(d)
Beispiel #40
0
class App(QMainWindow):
    def __init__(self, song):
        super().__init__()
        self.song_path = song
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.title = 'PyTunes'
        self.left = 300
        self.top = 300
        self.width = 300
        self.height = 150
        self.color = 0  # 0- toggle to dark 1- toggle to light
        self.userAction = -1  # 0- stopped, 1- playing 2-paused
        self.initUI()
        self.song = song

    def initUI(self):
        # Add file menu

        self.addControls()

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.toggleColors()
        self.show()

    def addControls(self):
        wid = QWidget(self)
        self.setCentralWidget(wid)
        # Add song controls
        volumeslider = QSlider(Qt.Horizontal, self)
        volumeslider.setFocusPolicy(Qt.NoFocus)
        volumeslider.valueChanged[int].connect(self.changeVolume)
        volumeslider.setValue(100)
        playBtn = QPushButton('Play')  # play button
        pauseBtn = QPushButton('Pause')  # pause button
        # Add button layouts
        controlArea = QVBoxLayout()  # centralWidget
        controls = QHBoxLayout()
        playlistCtrlLayout = QHBoxLayout()
        # Add buttons to song controls layout
        controls.addWidget(playBtn)
        controls.addWidget(pauseBtn)
        # Add buttons to playlist controls layout
        # Add to vertical layout
        controlArea.addWidget(volumeslider)
        controlArea.addLayout(controls)
        controlArea.addLayout(playlistCtrlLayout)
        wid.setLayout(controlArea)
        # Connect each signal to their appropriate function
        playBtn.clicked.connect(self.playhandler)
        pauseBtn.clicked.connect(self.pausehandler)

        self.statusBar()
        self.playlist.currentMediaChanged.connect(self.songChanged)

    def openFile(self):

        url = QUrl.fromLocalFile(self.song_path)

        self.playlist.addMedia(QMediaContent(url))
        self.player.setPlaylist(self.playlist)
        self.player.play()
        self.userAction = 1

    def addFiles(self):
        if self.playlist.mediaCount() != 0:
            self.folderIterator()
        else:
            self.folderIterator()
            self.player.setPlaylist(self.playlist)
            self.player.playlist().setCurrentIndex(0)
            self.player.play()
            self.userAction = 1

    def folderIterator(self):
        folderChosen = QFileDialog.getExistingDirectory(
            self, 'Open Music Folder', '~')
        if folderChosen != None:
            it = QDirIterator(folderChosen)
            it.next()
            while it.hasNext():
                if it.fileInfo().isDir() == False and it.filePath() != '.':
                    fInfo = it.fileInfo()
                    if fInfo.suffix() in ('mp3', 'ogg', 'wav', 'm4a'):
                        self.playlist.addMedia(
                            QMediaContent(QUrl.fromLocalFile(it.filePath())))
                it.next()
            if it.fileInfo().isDir() == False and it.filePath() != '.':
                fInfo = it.fileInfo()
                if fInfo.suffix() in ('mp3', 'ogg', 'wav', 'm4a'):
                    self.playlist.addMedia(
                        QMediaContent(QUrl.fromLocalFile(it.filePath())))

    def playhandler(self):
        if self.playlist.mediaCount() == 0:
            self.openFile()
        elif self.playlist.mediaCount() != 0:
            self.player.play()
            self.userAction = 1

    def pausehandler(self):
        self.userAction = 2
        self.player.pause()

    def changeVolume(self, value):
        self.player.setVolume(value)

    def songChanged(self, media):
        if not media.isNull():
            url = media.canonicalUrl()
            self.statusBar().showMessage(url.fileName())

    def toggleColors(self):
        """ Fusion dark palette from https://gist.github.com/QuantumCD/6245215. Modified by me and J.J. """
        app.setStyle("Fusion")
        palette = QPalette()
        if self.color == 0:
            palette.setColor(QPalette.Window, QColor(53, 53, 53))
            palette.setColor(QPalette.WindowText, Qt.white)
            palette.setColor(QPalette.Base, QColor(25, 25, 25))
            palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
            palette.setColor(QPalette.ToolTipBase, Qt.white)
            palette.setColor(QPalette.ToolTipText, Qt.white)
            palette.setColor(QPalette.Text, Qt.white)
            palette.setColor(QPalette.Button, QColor(53, 53, 53))
            palette.setColor(QPalette.ButtonText, Qt.white)
            palette.setColor(QPalette.BrightText, Qt.red)
            palette.setColor(QPalette.Link, QColor(235, 101, 54))
            palette.setColor(QPalette.Highlight, QColor(235, 101, 54))
            palette.setColor(QPalette.HighlightedText, Qt.black)
            app.setPalette(palette)
            self.color = 1
        elif self.color == 1:
            palette.setColor(QPalette.Window, Qt.white)
            palette.setColor(QPalette.WindowText, Qt.black)
            palette.setColor(QPalette.Base, QColor(240, 240, 240))
            palette.setColor(QPalette.AlternateBase, Qt.white)
            palette.setColor(QPalette.ToolTipBase, Qt.white)
            palette.setColor(QPalette.ToolTipText, Qt.white)
            palette.setColor(QPalette.Text, Qt.black)
            palette.setColor(QPalette.Button, Qt.white)
            palette.setColor(QPalette.ButtonText, Qt.black)
            palette.setColor(QPalette.BrightText, Qt.red)
            palette.setColor(QPalette.Link, QColor(66, 155, 248))
            palette.setColor(QPalette.Highlight, QColor(66, 155, 248))
            palette.setColor(QPalette.HighlightedText, Qt.black)
            app.setPalette(palette)
            self.color = 0
Beispiel #41
0
class Player(QMediaPlayer):

    player = None  # 播放器
    playList = None  # 播放列表
    source = None  # 音频路径
    content = None  # 音频内容
    musicSource = []  # 音频路劲列表
    MUSIC_PATH = './BackgroundMusic'

    def __init__(self, parent=None):
        super(Player, self).__init__(parent)

        self.getMusicSource()
        self.initPlayer()
        self.createPlayList()
        self.player.play()

    def getMusicSource(self):
        """获取音乐文件路径"""
        for src in os.listdir(self.MUSIC_PATH):
            self.musicSource.append('{}/{}'.format(self.MUSIC_PATH, src))

    def initPlayer(self):
        """初始化播放器"""
        self.player = QMediaPlayer(self)  # 创建播放器
        self.playList = QMediaPlaylist(self.player)  # 播放列表
        self.playList.setPlaybackMode(QMediaPlaylist.CurrentItemInLoop)  # 播放模式
        """
        QMediaPlaylist.CurrentItemOnce       0->播放一次
        QMediaPlaylist.CurrentItemInLoop     1->单曲循环
        QMediaPlaylist.Sequential            2->顺序播放
        QMediaPlaylist.Loop                  3->列表循环
        QMediaPlaylist.Random                4->随机播放
        """

    def createPlayList(self):
        """创建播放列表"""
        self.playList.clear()
        for path in self.musicSource:
            self.content = QMediaContent(QUrl.fromLocalFile(path))
            self.playList.addMedia(self.content)
        self.player.setPlaylist(self.playList)  # 创建播放列表
        # print(self.player.currentMedia().canonicalUrl().path())  # 输出音乐文件路径

    def nextMusic(self):
        """播放下一首音乐"""
        if self.playList.currentIndex() == len(self.musicSource) - 1:
            index = 0
        else:
            index = self.playList.currentIndex() + 1

        self.playList.setCurrentIndex(index)
        self.player.play()

    def previousMusic(self):
        """播放前一首音乐"""
        if self.playList.currentIndex() == 0:
            index = len(self.musicSource) - 1
        else:
            index = self.playList.currentIndex() - 1

        self.playList.setCurrentIndex(index)
        self.player.play()

    def mute(self):
        """静音"""
        self.player.setMuted(True)

    def cancelMute(self):
        """取消静音"""
        self.player.setMuted(False)
Beispiel #42
0
class Music(QMainWindow):
    def __init__(self, parent=None):
        super().__init__()
        uic.loadUi(QDir.current().absoluteFilePath('music.ui'), self)
        #print(QDir.current().absoluteFilePath('music.ui'))
        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)
        self.playMusicBtn.clicked.connect(self.player.play)
        self.pauseMusicBtn.clicked.connect(self.player.pause)
        self.stopMusicBtn.clicked.connect(self.player.stop)
        self.nextMusicBtn.clicked.connect(self.playlist.next)
        self.previousMusicButton.clicked.connect(self.playlist.previous)
        self.openFilesBtn.clicked.connect(self.openFiles)
        self.openDirectoryBtn.clicked.connect(self.openDir)
        self.playlist.currentMediaChanged.connect(self.updateLabels)
        self.show()

    def buildPlayList(self, fileNames):
        for name in fileNames:
            print(name)
            url = QUrl.fromLocalFile(name)
            self.playlist.addMedia(QMediaContent(url))
            #self.playlist.setPlaybackMode(QMediaPlaylist.Loop)

    def openFiles(self):
        #fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files")
        music = QStandardPaths.writableLocation(QStandardPaths.MusicLocation)
        path, _ = QFileDialog.getOpenFileName(
            self,
            "Open file",
            directory=music,
            options=QFileDialog.DontUseNativeDialog)
        print(type(path))
        print(path)
        self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(path)))

        print(type(path))
        print(path)

    def openDir(self):
        #dir _ = QtGui.QFileDialog.getExistingDirectory(None, 'Select a directory:', 'C:\\', QtGui.QFileDialog.ShowDirsOnly)
        home = QStandardPaths.writableLocation(QStandardPaths.HomeLocation)
        d = QFileDialog.getExistingDirectory(
            caption="Choose Directory",
            directory=home,
            options=QFileDialog.DontUseNativeDialog)
        #print(x)
        files = os.listdir(d)
        #print(type(files))
        for i in files:
            path = os.path.join(d, i)
            self.playlist.addMedia(QMediaContent(QUrl.fromLocalFile(path)))
            #print('{} {}'.format(path, type(i)))

        #print(os.listdir(path=x))
        #self.buildPlayList(os.listdir(path=x))
        songCount = self.playlist.mediaCount()
        self.songsLoadedLbl.setText('Songs Loaded = {}'.format(songCount))

    def updateLabels(self, media=None):
        #print(media)
        self.statusBar().showMessage(str(media.canonicalUrl().fileName()))
Beispiel #43
-1
class Player(QWidget):

    fullScreenChanged = pyqtSignal(bool)

    def __init__(self, playlist, parent=None):
        super(Player, self).__init__(parent)

        self.colorDialog = None
        self.trackInfo = ""
        self.statusInfo = ""
        self.duration = 0

        self.player = QMediaPlayer()
        self.playlist = QMediaPlaylist()
        self.player.setPlaylist(self.playlist)

        self.player.durationChanged.connect(self.durationChanged)
        self.player.positionChanged.connect(self.positionChanged)
        self.player.metaDataChanged.connect(self.metaDataChanged)
        self.playlist.currentIndexChanged.connect(self.playlistPositionChanged)
        self.player.mediaStatusChanged.connect(self.statusChanged)
        self.player.bufferStatusChanged.connect(self.bufferingProgress)
        self.player.videoAvailableChanged.connect(self.videoAvailableChanged)
        self.player.error.connect(self.displayErrorMessage)

        self.videoWidget = VideoWidget()
        self.player.setVideoOutput(self.videoWidget)

        self.playlistModel = PlaylistModel()
        self.playlistModel.setPlaylist(self.playlist)

        self.playlistView = QListView()
        self.playlistView.setModel(self.playlistModel)
        self.playlistView.setCurrentIndex(
                self.playlistModel.index(self.playlist.currentIndex(), 0))

        self.playlistView.activated.connect(self.jump)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(0, self.player.duration() / 1000)

        self.labelDuration = QLabel()
        self.slider.sliderMoved.connect(self.seek)

        self.labelHistogram = QLabel()
        self.labelHistogram.setText("Histogram:")
        self.histogram = HistogramWidget()
        histogramLayout = QHBoxLayout()
        histogramLayout.addWidget(self.labelHistogram)
        histogramLayout.addWidget(self.histogram, 1)

        self.probe = QVideoProbe()
        self.probe.videoFrameProbed.connect(self.histogram.processFrame)
        self.probe.setSource(self.player)

        openButton = QPushButton("Open", clicked=self.open)

        controls = PlayerControls()
        controls.setState(self.player.state())
        controls.setVolume(self.player.volume())
        controls.setMuted(controls.isMuted())

        controls.play.connect(self.player.play)
        controls.pause.connect(self.player.pause)
        controls.stop.connect(self.player.stop)
        controls.next.connect(self.playlist.next)
        controls.previous.connect(self.previousClicked)
        controls.changeVolume.connect(self.player.setVolume)
        controls.changeMuting.connect(self.player.setMuted)
        controls.changeRate.connect(self.player.setPlaybackRate)
        controls.stop.connect(self.videoWidget.update)

        self.player.stateChanged.connect(controls.setState)
        self.player.volumeChanged.connect(controls.setVolume)
        self.player.mutedChanged.connect(controls.setMuted)

        self.fullScreenButton = QPushButton("FullScreen")
        self.fullScreenButton.setCheckable(True)

        self.colorButton = QPushButton("Color Options...")
        self.colorButton.setEnabled(False)
        self.colorButton.clicked.connect(self.showColorDialog)

        displayLayout = QHBoxLayout()
        displayLayout.addWidget(self.videoWidget, 2)
        displayLayout.addWidget(self.playlistView)

        controlLayout = QHBoxLayout()
        controlLayout.setContentsMargins(0, 0, 0, 0)
        controlLayout.addWidget(openButton)
        controlLayout.addStretch(1)
        controlLayout.addWidget(controls)
        controlLayout.addStretch(1)
        controlLayout.addWidget(self.fullScreenButton)
        controlLayout.addWidget(self.colorButton)

        layout = QVBoxLayout()
        layout.addLayout(displayLayout)
        hLayout = QHBoxLayout()
        hLayout.addWidget(self.slider)
        hLayout.addWidget(self.labelDuration)
        layout.addLayout(hLayout)
        layout.addLayout(controlLayout)
        layout.addLayout(histogramLayout)

        self.setLayout(layout)

        if not self.player.isAvailable():
            QMessageBox.warning(self, "Service not available",
                    "The QMediaPlayer object does not have a valid service.\n"
                    "Please check the media service plugins are installed.")

            controls.setEnabled(False)
            self.playlistView.setEnabled(False)
            openButton.setEnabled(False)
            self.colorButton.setEnabled(False)
            self.fullScreenButton.setEnabled(False)

        self.metaDataChanged()

        self.addToPlaylist(playlist)

    def open(self):
        fileNames, _ = QFileDialog.getOpenFileNames(self, "Open Files")
        self.addToPlaylist(fileNames)

    def addToPlaylist(self, fileNames):
        for name in fileNames:
            fileInfo = QFileInfo(name)
            if fileInfo.exists():
                url = QUrl.fromLocalFile(fileInfo.absoluteFilePath())
                if fileInfo.suffix().lower() == 'm3u':
                    self.playlist.load(url)
                else:
                    self.playlist.addMedia(QMediaContent(url))
            else:
                url = QUrl(name)
                if url.isValid():
                    self.playlist.addMedia(QMediaContent(url))

    def durationChanged(self, duration):
        duration /= 1000

        self.duration = duration
        self.slider.setMaximum(duration)

    def positionChanged(self, progress):
        progress /= 1000

        if not self.slider.isSliderDown():
            self.slider.setValue(progress)

        self.updateDurationInfo(progress)

    def metaDataChanged(self):
        if self.player.isMetaDataAvailable():
            self.setTrackInfo("%s - %s" % (
                    self.player.metaData(QMediaMetaData.AlbumArtist),
                    self.player.metaData(QMediaMetaData.Title)))

    def previousClicked(self):
        # Go to the previous track if we are within the first 5 seconds of
        # playback.  Otherwise, seek to the beginning.
        if self.player.position() <= 5000:
            self.playlist.previous()
        else:
            self.player.setPosition(0)

    def jump(self, index):
        if index.isValid():
            self.playlist.setCurrentIndex(index.row())
            self.player.play()

    def playlistPositionChanged(self, position):
        self.playlistView.setCurrentIndex(
                self.playlistModel.index(position, 0))

    def seek(self, seconds):
        self.player.setPosition(seconds * 1000)

    def statusChanged(self, status):
        self.handleCursor(status)

        if status == QMediaPlayer.LoadingMedia:
            self.setStatusInfo("Loading...")
        elif status == QMediaPlayer.StalledMedia:
            self.setStatusInfo("Media Stalled")
        elif status == QMediaPlayer.EndOfMedia:
            QApplication.alert(self)
        elif status == QMediaPlayer.InvalidMedia:
            self.displayErrorMessage()
        else:
            self.setStatusInfo("")

    def handleCursor(self, status):
        if status in (QMediaPlayer.LoadingMedia, QMediaPlayer.BufferingMedia, QMediaPlayer.StalledMedia):
            self.setCursor(Qt.BusyCursor)
        else:
            self.unsetCursor()

    def bufferingProgress(self, progress):
        self.setStatusInfo("Buffering %d%" % progress)

    def videoAvailableChanged(self, available):
        if available:
            self.fullScreenButton.clicked.connect(
                    self.videoWidget.setFullScreen)
            self.videoWidget.fullScreenChanged.connect(
                    self.fullScreenButton.setChecked)

            if self.fullScreenButton.isChecked():
                self.videoWidget.setFullScreen(True)
        else:
            self.fullScreenButton.clicked.disconnect(
                    self.videoWidget.setFullScreen)
            self.videoWidget.fullScreenChanged.disconnect(
                    self.fullScreenButton.setChecked)

            self.videoWidget.setFullScreen(False)

        self.colorButton.setEnabled(available)

    def setTrackInfo(self, info):
        self.trackInfo = info

        if self.statusInfo != "":
            self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo))
        else:
            self.setWindowTitle(self.trackInfo)

    def setStatusInfo(self, info):
        self.statusInfo = info

        if self.statusInfo != "":
            self.setWindowTitle("%s | %s" % (self.trackInfo, self.statusInfo))
        else:
            self.setWindowTitle(self.trackInfo)

    def displayErrorMessage(self):
        self.setStatusInfo(self.player.errorString())

    def updateDurationInfo(self, currentInfo):
        duration = self.duration
        if currentInfo or duration:
            currentTime = QTime((currentInfo/3600)%60, (currentInfo/60)%60,
                    currentInfo%60, (currentInfo*1000)%1000)
            totalTime = QTime((duration/3600)%60, (duration/60)%60,
                    duration%60, (duration*1000)%1000);

            format = 'hh:mm:ss' if duration > 3600 else 'mm:ss'
            tStr = currentTime.toString(format) + " / " + totalTime.toString(format)
        else:
            tStr = ""

        self.labelDuration.setText(tStr)

    def showColorDialog(self):
        if self.colorDialog is None:
            brightnessSlider = QSlider(Qt.Horizontal)
            brightnessSlider.setRange(-100, 100)
            brightnessSlider.setValue(self.videoWidget.brightness())
            brightnessSlider.sliderMoved.connect(
                    self.videoWidget.setBrightness)
            self.videoWidget.brightnessChanged.connect(
                    brightnessSlider.setValue)

            contrastSlider = QSlider(Qt.Horizontal)
            contrastSlider.setRange(-100, 100)
            contrastSlider.setValue(self.videoWidget.contrast())
            contrastSlider.sliderMoved.connect(self.videoWidget.setContrast)
            self.videoWidget.contrastChanged.connect(contrastSlider.setValue)

            hueSlider = QSlider(Qt.Horizontal)
            hueSlider.setRange(-100, 100)
            hueSlider.setValue(self.videoWidget.hue())
            hueSlider.sliderMoved.connect(self.videoWidget.setHue)
            self.videoWidget.hueChanged.connect(hueSlider.setValue)

            saturationSlider = QSlider(Qt.Horizontal)
            saturationSlider.setRange(-100, 100)
            saturationSlider.setValue(self.videoWidget.saturation())
            saturationSlider.sliderMoved.connect(
                    self.videoWidget.setSaturation)
            self.videoWidget.saturationChanged.connect(
                    saturationSlider.setValue)

            layout = QFormLayout()
            layout.addRow("Brightness", brightnessSlider)
            layout.addRow("Contrast", contrastSlider)
            layout.addRow("Hue", hueSlider)
            layout.addRow("Saturation", saturationSlider)

            button = QPushButton("Close")
            layout.addRow(button)

            self.colorDialog = QDialog(self)
            self.colorDialog.setWindowTitle("Color Options")
            self.colorDialog.setLayout(layout)

            button.clicked.connect(self.colorDialog.close)

        self.colorDialog.show()