在 Tkinter 按鈕被按下時如何播放聲音?


Python 有許多用於構建各種應用程式介面和元件的內建庫和模組。Pygame 是用於設計和構建影片遊戲和音樂的 python 模組之一。它提供了混合所有聲音相關活動的混合。使用music 子模組,你可以流式傳輸 mp3、ogg 和其他各種聲音。

要建立一個在點選按鈕時播放聲音的應用程式,我們必須遵循以下步驟,

  • 確保Pygame 已安裝在你的本地計算機中。你可以使用pip install pygame 命令安裝pygame

  • 使用pygame.mixture.init() 初始化Pygame 混合。

  • 建立一個按鈕小元件,在播放音樂時使用它。

  • 定義一個函式play_sound() ,並透過指定mixture.load.music(filename) 中的檔案位置載入音樂。

  • 新增mixture.music.play() 播放音樂。

示例

# Import the required libraries
from tkinter import *
import pygame
from PIL import Image, ImageTk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x500")

# Add a background image
bg = ImageTk.PhotoImage(file="music.jpg")

label = Label(win, image=bg)
label.place(x=0, y=0)

# Initialize mixer module in pygame
pygame.mixer.init()

# Define a function to play the music
def play_sound():
   pygame.mixer.music.load("sample1.mp3")
   pygame.mixer.music.play()

# Add a Button widget
b1 = Button(win, text="Play Music", command=play_sound)
b1.pack(pady=60)

win.mainloop()

輸出

如果我們執行以上程式碼,它會顯示一個帶有一個按鈕的視窗。現在,在給定的函式中新增音樂位置以在應用程式中播放音樂。

更新日期:18-06-2021

3K+ 檢視次數

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.