File size: 1,419 Bytes
ade4f6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import pygame
import librosa

def play_audio(audio_path, volume=0.7):
    pygame.mixer.init()  # 初始化 pygame 的音频模块
    try:
        pygame.mixer.music.load(audio_path)  # 加载音频文件
        pygame.mixer.music.set_volume(volume)
        pygame.mixer.music.play()
        print(f"开始播放: {audio_path}")
    except pygame.error as e:
        print(f"播放音频文件时发生错误: {e}")
    # finally:
    #     pygame.mixer.quit()  # 退出 pygame 的音频模块

def play_audio_until_end(audio_path, volume=0.7):
    pygame.mixer.init()  # 初始化 pygame 的音频模块
    try:
        pygame.mixer.music.load(audio_path)  # 加载音频文件
        pygame.mixer.music.set_volume(volume)
        pygame.mixer.music.play()
        print(f"开始播放: {audio_path}")
        while pygame.mixer.music.get_busy():  # 等待音频播放结束
            pygame.time.Clock().tick(100)  # 控制循环速度,避免 CPU 占用过高
        print("音频播放结束")
    except pygame.error as e:
        print(f"播放音频文件时发生错误: {e}")
    # finally:
    #     pygame.mixer.quit()  # 退出 pygame 的音频模块

def get_length(audio_path):
    try:
        duration = librosa.get_duration(path=audio_path)
        print(f"音频时长: {duration} 秒")
        return duration
    except Exception as e:
        print(f"获取音频时长时发生错误: {e}")