日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

如何利用Python實(shí)現(xiàn)簡易的音頻播放器_python

作者:LeBron?Le ? 更新時(shí)間: 2022-05-03 編程語言

1. 需要用到的Python庫

  • pygame
  • tkinter

2. 簡易UI設(shè)計(jì)

audio_player = Tk()
audio_player.title('Audio Player v1.0')
audio_player.geometry('100x100+570+200')
audio_player.maxsize(height=110, width=220)
audio_player.minsize(height=110, width=220)

3. 功能模塊實(shí)現(xiàn)

3.1 選擇音頻文件進(jìn)行播放

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 控制音頻音量大小

這里可以定義一個(gè)全局變量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 播放器初始化等細(xì)節(jié)

def playAudio():
? ? try:
? ? ? ? mixer.init()
? ? ? ? mixer.music.load(filePath)
? ? ? ? mixer.music.set_volume(x)
? ? ? ? playBtn.config(text='pause')
? ? ? ? mixer.music.play()
? ? except:
? ? ? ? pass

4. 運(yùn)行

frame = Frame(app)
frame.place(x=35, y=20)

openBtn = Button(frame, text='OpenFile', command=selectFile, width=8).grid(row=0, column=1)

audioDec = Button(frame, text='?', command=lambda: audioDEC(x)).grid(row=1, column=0)
playBtn = Button(frame, text='...', command=playStop, width=8)
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, width=8).grid(row=2, column=1)

app.mainloop()

5. 簡易音頻播放器展示圖

  • ①點(diǎn)擊“OpenFile”按鈕可以打開本地音頻文件
  • ②“?”和“?”分別控制音量的減小和增大
  • ③點(diǎn)擊"Restart"按鈕可以重新播放當(dāng)前選中的音頻

6. 總結(jié)

本文僅僅是實(shí)現(xiàn)了一個(gè)簡易的音頻播放器,UI極其簡陋,為了僅僅是實(shí)現(xiàn)音頻播放的功能,僅供學(xué)習(xí)參考。

原文鏈接:https://blog.csdn.net/hutianle/article/details/123204633

欄目分類
最近更新