What if the favorite songs are not on the same platform? You need your own music player

 

 

Preface

Netease cloud music, QQ music and cool dog music are music software we often use. Of course, sometimes we need to jump on major music platforms because of a song, so we can create a music player by ourselves using python

Knowledge points:
1.python basic knowledge
2.requests Library
3.time
4.pygame
5.tkinter
6. Thread

Environmental Science:

windows + pycharm + python3

Suitable for students with zero Foundation

1. Import tool

from PyQt5 import QtWidgets,QtGui,QtCore
from PyQt5.QtMultimedia import QMediaContent,QMediaPlayer
import qtawesome as qta
import requests,traceback

2. Create a class

class Music(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        # Window size
        self.setFixedSize(400,200)
        # Title
        self.setWindowTitle("Mark")
        # Initialization interface
        self.init_ui()
        # Style
        self.custom_style()
        #
        self.playing = False # Play state initialized to no
        self.player = QMediaPlayer(self)

        self.timer = QtCore.QTimer()
        self.timer.setInterval(1000)
        self.timer.start()
        self.timer.timeout.connect(self.check_music_status)

3. Style

 

def custom_style(self):
        self.setStyleSheet('''
            #main_widget{
                border-radius:5px;
            }
            #play_btn,#pervious_btn,#next_btn{
                border:none;
            }
            #play_btn:hover,#pervious_btn:hover,#next_btn:hover{
                background:gray;
                border-radius:5px;
                cursor:pointer;
            }
        ''')
        self.close_btn.setStyleSheet('''
            QPushButton{
                background:#F76677;
                border-radius:5px;
                }
            QPushButton:hover{
                background:red;
                }''')
        self.status_label.setStyleSheet('''
            QLabel{
                background:#F7D674;
                border-radius:5px;
                }
        ''')

4. Initialize UI interface

def init_ui(self):
        # Window layout
        self.main_widget = QtWidgets.QWidget()
        self.main_widget.setObjectName("main_widget")
        self.main_layout = QtWidgets.QGridLayout()
        self.main_widget.setLayout(self.main_layout)

        # Title
        self.title_lable = QtWidgets.QLabel("Music is the source of sound")

        # close button
        self.close_btn = QtWidgets.QPushButton("")  # close button
        self.close_btn.clicked.connect(self.close_btn_event)
        self.close_btn.setFixedSize(15,15)

        # Music status button
        self.status_label = QtWidgets.QLabel("")
        # self.swith_btn.clicked.connect(self.swith_background)
        self.status_label.setFixedSize(15,15)

        # Play button
        play_icon = qta.icon("fa.play-circle",)
        self.play_btn = QtWidgets.QPushButton(play_icon,"")
        self.play_btn.setIconSize(QtCore.QSize(80, 80))
        self.play_btn.setFixedSize(82,82)
        self.play_btn.setObjectName("play_btn")
        self.play_btn.clicked.connect(self.play_music)

        # Next button
        next_icon = qta.icon("fa.play-circle-o")
        self.next_btn = QtWidgets.QPushButton(next_icon,"")
        self.next_btn.setIconSize(QtCore.QSize(80,80))
        self.next_btn.setFixedSize(82,82)
        self.next_btn.setObjectName("next_btn")
        self.next_btn.clicked.connect(self.next_music)

        # progress bar
        self.process_bar = QtWidgets.QProgressBar()
        self.process_value = 0
        self.process_bar.setValue(self.process_value)
        self.process_bar.setFixedHeight(5)
        self.process_bar.setTextVisible(False)

        self.main_layout.addWidget(self.close_btn,0,0,1,1)
        self.main_layout.addWidget(self.title_lable,0,1,1,1)
        self.main_layout.addWidget(self.status_label,1,0,1,1)
        self.main_layout.addWidget(self.play_btn, 1, 1, 1, 1)
        self.main_layout.addWidget(self.next_btn, 1, 2, 1, 1)
        self.main_layout.addWidget(self.process_bar,2,0,1,3)

        self.setCentralWidget(self.main_widget)

        # self.setWindowOpacity(0.9) # Set window transparency
        # self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # Set window background transparency
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)  # Hide border

5. Function settings of player

# close program
    def close_btn_event(self):
        self.close()

    # Mouse long press event
    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.m_drag = True
            self.m_DragPosition = event.globalPos() - self.pos()
            event.accept()
            self.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))

    # Mouse movement events
    def mouseMoveEvent(self, QMouseEvent):
        if QtCore.Qt.LeftButton and self.m_drag:
            self.move(QMouseEvent.globalPos() - self.m_DragPosition)
            QMouseEvent.accept()

    # Mouse release event
    def mouseReleaseEvent(self, QMouseEvent):
        self.m_drag = False
        self.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))

    # Play music
    def play_music(self):
        try:
            # Play music
            if self.playing is False:
                self.playing = True # Set playback status to yes
                self.play_btn.setIcon(qta.icon("fa.pause-circle")) # Set playback Icon
                player_status = self.player.mediaStatus() # Get player status
                # print("Current playback status:",player_status)
                if player_status == 6:
                    # Set status label to green
                    self.status_label.setStyleSheet('''QLabel{background:#6DDF6D;border-radius:5px;}''')
                    self.player.play()
                else:
                    self.next_music()
            # Pause music
            else:
                # Set status to blue
                self.status_label.setStyleSheet('''QLabel{background:#0099CC;border-radius:5px;}''')
                self.playing = False
                self.play_btn.setIcon(qta.icon("fa.play-circle"))
                self.player.pause()
        except Exception as e:
            print(repr(e))

    # Next music
    def next_music(self):
        try:
            # Set status to yellow
            self.status_label.setStyleSheet('''
                QLabel{
                    background:#F7D674;
                    border-radius:5px;
                    }
            ''')
            self.playing = True  # Set playback status to yes
            self.play_btn.setIcon(qta.icon("fa.pause-circle"))  # Modify playback Icon
            self.process_value = 0  # Reset progress value

            # Get online songs
            self.get_music_thread = GetMusicThread()
            self.get_music_thread.finished_signal.connect(self.init_player)
            self.get_music_thread.start()
        except Exception as e:
            print(traceback.print_exc())

    # Set up player
    def init_player(self,url):
        # print("Get music links:",url)
        content = QMediaContent(QtCore.QUrl(url))
        self.player.setMedia(content)
        self.player.setVolume(50)
        self.player.play()
        self.duration = self.player.duration()  # The length of music
        # Set status to green
        self.status_label.setStyleSheet('''
            QLabel{
                background:#6DDF6D;
                border-radius:5px;
                }
        ''')

        # Progress bar timer
        self.process_timer = QtCore.QTimer()
        self.process_timer.setInterval(1000)
        self.process_timer.start()
        self.process_timer.timeout.connect(self.process_timer_status)

    # timer
    def check_music_status(self):
        player_status = self.player.mediaStatus()
        player_duration = self.player.duration()
        # print("Music time:",player_duration)
        # print("Current player status",player_status)
        if player_status == 7:
            self.next_music()

        if player_duration > 0:
            self.duration = player_duration

    # Progress bar timer
    def process_timer_status(self):
        try:
            if self.playing is True:
                self.process_value += (100 / (self.duration/1000))
                # print("Current progress:",self.process_value)
                self.process_bar.setValue(self.process_value)
        except Exception as e:
            print(repr(e))

Run the code, the effect is as follows:

 

 

 

 

If you want to learn Python or are learning python, there are many Python tutorials, but are they up to date? Maybe you have learned something that someone else probably learned two years ago. Share a wave of the latest Python tutorials in 2020 in this editor. Access to the way, private letter small "information", you can get free Oh!

Tags: Python Qt Windows Pycharm

Posted on Thu, 07 May 2020 08:34:41 -0700 by BTalon