TestTranslator / lib /audio.py
yujuanqin's picture
refactor: move code to lib
fa3606d
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}")