用python写一个音乐播放器
时间: 2024-05-16 09:16:47 浏览: 22
好的,以下是一个简单的音乐播放器的Python代码示例:
```python
import os
import pygame
# 初始化Pygame
pygame.init()
# 设置窗口标题
pygame.display.set_caption("Music Player")
# 定义常量
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
WHITE_COLOR = (255, 255, 255)
BLACK_COLOR = (0, 0, 0)
# 创建窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 加载音乐文件列表
music_files = ["music1.mp3", "music2.mp3", "music3.mp3"]
current_music = 0
# 加载第一首音乐
pygame.mixer.music.load(music_files[current_music])
pygame.mixer.music.play()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
# 切换到下一首音乐
current_music += 1
if current_music >= len(music_files):
current_music = 0
pygame.mixer.music.load(music_files[current_music])
pygame.mixer.music.play()
# 绘制背景
screen.fill(WHITE_COLOR)
# 绘制文字
font = pygame.font.Font(None, 36)
text = font.render(music_files[current_music], True, BLACK_COLOR)
screen.blit(text, (SCREEN_WIDTH / 2 - text.get_width() / 2, SCREEN_HEIGHT / 2 - text.get_height() / 2))
# 更新屏幕
pygame.display.update()
```
这个示例使用了Pygame库来创建窗口和播放音乐。它加载了一个音乐文件列表,并允许用户使用空格键切换到下一首音乐。在窗口中心,它显示了当前播放的音乐文件名。你可以根据自己的需要修改代码来满足不同的需求。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)