Python制作9行最简单音乐播放器?不,我不满足

Posted 蚂蚁爱Python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python制作9行最简单音乐播放器?不,我不满足相关的知识,希望对你有一定的参考价值。

人生苦短 我用python

好久不见啦~这次就来给大家整个大福利 ~

源码资料电子书:点击此处跳转文末名片获取

最简单的9行代码音乐播放器如下:

import time
import pygame

file = r'歌曲路径'
pygame.mixer.init()
print('正在播放',file)
track = pygame.mixer.music.load(file)
pygame.mixer.music.play()
time.sleep(130)
pygame.mixer.music.stop()

但是我不会满足哒~大家也不会满足的对吧 ~ ~ ~

所以给大家准备了有界面的音乐播放器

知识点 + 所需模块

1.python基础知识
2.requests库
3.time
4.pygame
5.tkinter
6.线程

环境

  • windows
  • pycharm 2021.2
  • python 3.8

完整代码,运行即可,记得三连👍👍👍

(直接明示了)

import os
import time
import tkinter
import tkinter.filedialog
import threading
import pygame  


root = tkinter.Tk()
root.title('音乐播放器')
root.geometry('460x600+500+100')
root.resizable(False,False) 

folder =''
res = []
num = 0
now_music = ''



def buttonChooseClick():
    """
    添加文件夹
    :return:
    """
    global folder
    global res
    if not folder:
        folder = tkinter.filedialog.askdirectory()
        musics = [folder + '\\\\' + music
                  for music in os.listdir(folder) \\
\\
                  if music.endswith(('.mp3','.wav','.ogg'))]
        ret = []
        for i in musics:
            ret.append(i.split('\\\\')[1:])
            res.append(i.replace('\\\\','/'))

        var2 = tkinter.StringVar()
        var2.set(ret)
        lb = tkinter.Listbox(root,listvariable=var2)
        lb.place(x=50,y=100,width=260,height=300)

    if not folder:
        return

    global playing
    playing = True
    buttonPlay['state'] = 'normal'
    buttonStop['state'] = 'normal'
    # python学习交流裙:660193417#
    pause_resume.set('播放')

def play():
    """
    播放音乐
    :return:
    """
    if len(res):
        pygame.mixer.init()
        global num
        while playing:
            if not pygame.mixer.music.get_busy():
                netxMusic = res[num]
                print(netxMusic)
                print(num)
                pygame.mixer.music.load(netxMusic.encode())
                pygame.mixer.music.play(1)
                if len(res) -1 == num:
                    num = 0
                else:
                    num = num + 1
                netxMusic = netxMusic.split('\\\\')[1:]
                musicName.set('playing......' + ''.join(netxMusic))



def buttonPlayClick():
    """
    点击播放
    :return:
    """
    buttonNext['state'] = 'normal'

    if pause_resume.get() == '播放':
        pause_resume.set('暂停')
        global folder

        if not folder:
            folder = tkinter.filedialog.askdirectory()

        if not folder:
            return

        global playing

        playing = True

        t = threading.Thread(target=play)
        t.start()

    elif pause_resume.get() == '暂停':
        pygame.mixer.music.pause()

        pause_resume.set('继续')

    elif pause_resume.get() == '继续':
        pygame.mixer.music.unpause()

        pause_resume.set('暂停')



def buttonStopClick():
    """
    停止播放
    :return:
    """
    global playing
    playing = False
    pygame.mixer.music.stop()


def buttonNextClick():
    """
    下一首
    :return:
    """
    global playing
    playing = False
    pygame.mixer.music.stop()
    global num
    if len(res) == num:
        num = 0

    playing = True
    t = threading.Thread(target=play)
    t.start()


def closeWindow():
    """
    关闭窗口
    :return:
    """

    global playing

    playing = False

    time.sleep(0.3)

    try:


        pygame.mixer.music.stop()

        pygame.mixer.quit()

    except:

        pass

    root.destroy()


def control_voice(value=0.5):
    """
    声音控制
    :param value: 0.0-1.0
    :return:
    """
    pygame.mixer.music.set_volume(float(value))


def buttonPrevClick():
    """
    上一首
    :return:
    """
    global playing

    playing = False

    pygame.mixer.music.stop()

    global num
  
    if num == 0:
        num = len(res) - 2
    elif num == len(res) - 1:
        num -= 2
    else:
        num -= 2
    print(num)

    playing = True



    t = threading.Thread(target=play)

    t.start()



root.protocol('WM_DELETE_WINDOW', closeWindow)


buttonChoose = tkinter.Button(root,text='添加',command=buttonChooseClick)

buttonChoose.place(x=50,y=10,width=50,height=20)


pause_resume = tkinter.StringVar(root,value='播放')
buttonPlay = tkinter.Button(root,textvariable=pause_resume,command=buttonPlayClick)
buttonPlay.place(x=190,y=10,width=50,height=20)
buttonPlay['state'] = 'disabled'


buttonStop = tkinter.Button(root, text='停止',command=buttonStopClick)
buttonStop.place(x=120, y=10, width=50, height=20)
buttonStop['state'] = 'disabled'

buttonNext = tkinter.Button(root, text='下一首',command=buttonNextClick)
buttonNext.place(x=260, y=10, width=50, height=20)
buttonNext['state'] = 'disabled'
buttonPrev = tkinter.Button(root, text='上一首',command=buttonPrevClick)
buttonPrev.place(x=330, y=10, width=50, height=20)
buttonPrev['state'] = 'disabled'


musicName = tkinter.StringVar(root, value='暂时没有播放音乐...')
labelName = tkinter.Label(root, textvariable=musicName)
labelName.place(x=10, y=30, width=260, height=20)


s = tkinter.Scale(root, label='音量', from_=0, to=1, orient=tkinter.HORIZONTAL,
                  length=240, showvalue=0, tickinterval=2, resolution=0.1,command=control_voice)
s.place(x=50, y=50, width=200)


root.mainloop()

效果展示

简易版的

半成品,代码没写完(诶嘿我懒)

👇问题解答 · 源码获取 · 技术交流 · 抱团学习请联系👇

Python带你制作一个属于自己的多功能音乐播放器

前言

嗨喽,大家好呀~这里是爱看美女的茜茜呐

就是用Python做一个简易的音乐播放器,废话不多说,咱们直接开干

当然,今天做这个肯定不是最简单的,最简单的音乐播放器,9行代码足以


完整源码等直接在文末名片领取。点击此处跳转


简易播放器

代码展示

导入模块

import time
import pygame
file = r'歌曲路径'
pygame.mixer.init()
print('正在播放',file)
track = pygame.mixer.music.load(file)
pygame.mixer.music.play()
time.sleep(130)
pygame.mixer.music.stop()

效果展示

多功能播放器

知识点和所需模块

  1. python基础知识

  2. requests库

  3. time

  4. pygame

  5. tkinter

  6. 线程

如果安装python第三方模块:

  1. win + R 输入 cmd 点击确定, 输入安装命令 pip install 模块名 (pip install requests) 回车

  2. 在pycharm中点击Terminal(终端) 输入安装命令

环境

  • windows

  • pycharm 2021.2

  • python 3.8

代码展示

( 完整源码点击此处跳转跳转文末名片加入君羊,找管理员小姐姐领取呀~ )

导入模块

import os
import time
import tkinter
import tkinter.filedialog
import threading
import pygame   # pip
root = tkinter.Tk()
root.title('音乐播放器')
root.geometry('460x600+500+100')
root.resizable(False,False)  # 不能拉伸

folder =''
res = []
num = 0
now_music = ''

添加文件夹

def buttonChooseClick():

    global folder
    global res
    if not folder:
        folder = tkinter.filedialog.askdirectory()
        musics = [folder + '\\\\' + music
                  for music in os.listdir(folder) \\
\\
                  if music.endswith(('.mp3','.wav','.ogg'))]
        ret = []
        for i in musics:
            ret.append(i.split('\\\\')[1:])
            res.append(i.replace('\\\\','/'))

        var2 = tkinter.StringVar()
        var2.set(ret)
        lb = tkinter.Listbox(root,listvariable=var2)
        lb.place(x=50,y=100,width=260,height=300)

    if not folder:
        return

    global playing
    playing = True

根据情况禁用和启用相应的按钮

    buttonPlay['state'] = 'normal'
    buttonStop['state'] = 'normal'
    # buttonPause['state'] = 'normal'
    pause_resume.set('播放')

播放音乐

def play():

    if len(res):
        pygame.mixer.init()
        global num
        while playing:
            if not pygame.mixer.music.get_busy():
                netxMusic = res[num]
                print(netxMusic)
                print(num)
                pygame.mixer.music.load(netxMusic.encode())
                # 播放
                pygame.mixer.music.play(1)
                if len(res) -1 == num:
                    num = 0
                else:
                    num = num + 1
                netxMusic = netxMusic.split('\\\\')[1:]
                musicName.set('playing......' + ''.join(netxMusic))
            else:
                time.sleep(0.1)

点击播放

def buttonPlayClick():

    buttonNext['state'] = 'normal'

    buttonPrev['state'] = 'normal'

选择要播放的音乐文件夹

    if pause_resume.get() == '播放':
        pause_resume.set('暂停')
        global folder

        if not folder:
            folder = tkinter.filedialog.askdirectory()

        if not folder:
            return

        global playing

        playing = True

创建一个线程来播放音乐,当前主线程用来接收用户操作

        t = threading.Thread(target=play)
        t.start()

    elif pause_resume.get() == '暂停':
        # pygame.mixer.init()
        pygame.mixer.music.pause()

        pause_resume.set('继续')

    elif pause_resume.get() == '继续':
        # pygame.mixer.init()
        pygame.mixer.music.unpause()

        pause_resume.set('暂停')

停止播放

def buttonStopClick():

    global playing
    playing = False
    pygame.mixer.music.stop()

下一首

def buttonNextClick():
    global playing
    playing = False
    pygame.mixer.music.stop()
    global num
    if len(res) == num:
        num = 0

    playing = True

创建线程播放音乐,主线程用来接收用户操作

    t = threading.Thread(target=play)
    t.start()

关闭窗口

def closeWindow():

修改变量,结束线程中的循环

    global playing

    playing = False

    time.sleep(0.3)

停止播放,如果已停止,

再次停止时会抛出异常,所以放在异常处理结构中

    try:

        pygame.mixer.music.stop()

        pygame.mixer.quit()

    except:

        pass

    root.destroy()

声音控制

def control_voice(value=0.5):
    pygame.mixer.music.set_volume(float(value))

上一首

def buttonPrevClick():
    global playing

    playing = False

    pygame.mixer.music.stop()
    #
    # pygame.mixer.quit()
    global num
    # num += 1
    # num -= 1
    if num == 0:
        num = len(res) - 2
        # num -= 1
    elif num == len(res) - 1:
        num -= 2
    else:
        num -= 2
        # num -= 1
    print(num)

    playing = True

创建一个线程来播放音乐,当前主线程用来接收用户操作

    t = threading.Thread(target=play)

    t.start()

窗口关闭

root.protocol('WM_DELETE_WINDOW', closeWindow)

效果展示



尾语

感谢你观看我的文章呐~本次航班到这里就结束啦 🛬

希望本篇文章有对你带来帮助 🎉,有学习到一点知识~

躲起来的星星🍥也在努力发光,你也要努力加油(让我们一起努力叭)。

最后,宣传一下呀~👇👇👇更多源码、资料、素材、解答、交流皆点击下方名片获取呀👇👇👇

以上是关于Python制作9行最简单音乐播放器?不,我不满足的主要内容,如果未能解决你的问题,请参考以下文章

python 本地音乐播放器制作过程

Python实现多功能音乐播放器

音乐播放制作(html css js)

团队作业9——事后分析(Beta版本)

Java:淡出音乐

如何用delphi编写音乐播放器