Python มีไลบรารีและโมดูลในตัวมากมายสำหรับสร้างอินเทอร์เฟซและส่วนประกอบแอปพลิเคชัน Pygame เป็นหนึ่งในโมดูล Python ใช้ออกแบบและสร้างเกมวิดีโอและเพลง มีการผสมผสานจัดการกิจกรรมเกี่ยวกับเสียงทั้งหมด ใช้โมดูลย่อย music สตรีม mp3, ogg และเสียงหลากหลายรูปแบบ
เพื่อสร้างแอปพลิเคชันที่เล่นเสียงเมื่อคลิกปุ่ม ให้ทำตามขั้นตอน:
- ตรวจสอบว่า Pygame ติดตั้งในเครื่องแล้ว ติดตั้งด้วย pip install pygame
- เริ่มต้น Pygame mixture ด้วย pygame.mixer.init()
- สร้าง Button widget สำหรับเล่นเพลง
- กำหนดฟังก์ชัน 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()ผลลัพธ์
การรันโค้ดจะแสดงหน้าต่างพร้อมปุ่ม ตอนนี้เพิ่มตำแหน่งไฟล์เพลงในฟังก์ชันเพื่อเล่นเพลงในแอปพลิเคชัน
