最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
利用Python实现简易的音频播放器代码示例
时间:2022-06-25 01:21:54 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下利用Python实现简易的音频播放器代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
1. 需要用到的Python库
pygame
tkinter
2. 简易UI设计
audio_player = Tk()
audio_player.title('Audio Player v1.0')
audio_player.geometry('100x100+570+200')
audio_player.maxsize(, )
audio_player.minsize(, )
3. 功能模块实现
3.1 选择音频文件进行播放
def selectFile():
file = filedialog.askopenfile(mode='r', filetypes=[('AudioFile', '*.mp3')])
global filePath
filePath = str(file).split("'")[1]
try:
playAudio()
except:
pass
3.2 控制音频播放、暂停
def changeText(text):
if text == 'play':
return 'pause'
if text == 'pause':
return 'play'
def playStop():
playBtn.config(text=changeText(playBtn.config('text')[4]))
if playBtn.config('text')[4] == 'pause':
mixer.music.unpause()
else:
if playBtn.config('text')[4] == 'play':
mixer.music.pause()
3.3 控制音频音量大小
这里可以定义一个全局变量x,初始化为值0.5。
def audioINC(y):
mixer.music.set_volume(y + 0.1)
global x
x += 0.1
def audioDEC(y):
mixer.music.set_volume(y - 0.1)
global x
x -= 0.1
3.4 播放器初始化等细节
def playAudio():
try:
mixer.init()
mixer.music.load(filePath)
mixer.music.set_volume(x)
playBtn.config(text='pause')
mixer.music.play()
except:
pass
4. 运行
frame = Frame(app) frame.place(x=35, y=20) openBtn = Button(frame, text='OpenFile', command=selectFile, ).grid(row=0, column=1) audioDec = Button(frame, text='➖', command=lambda: audioDEC(x)).grid(row=1, column=0) playBtn = Button(frame, text='...', command=playStop, ) playBtn.grid(row=1, column=1) audioInc = Button(frame, text='➕', command=lambda: audioINC(x)).grid(row=1, column=2) restartBtn = Button(frame, text='Restart', command=playAudio, ).grid(row=2, column=1) app.mainloop()
5. 简易音频播放器展示图
①点击“OpenFile”按钮可以打开本地音频文件
②“➖”和“➕”分别控制音量的减小和增大
③点击"Restart"按钮可以重新播放当前选中的音频
相关文章
- 超自然行动组礼包兑换码有哪些 2025最新可用兑换码合集 11-05
- 逃离鸭科夫怎么刷刀 逃离鸭科夫刷刀方法介绍 11-05
- 逃离鸭科夫怎么解锁农场小镇 农场小镇解锁攻略 11-05
- 梦幻消除战座无虚席有什么玩法技巧 11-05
- 适合跨年的句子 11-05
- 忘川风华录周瑜怎么培养 11-05
