Open
Description
可否添加一个读音功能, 可以使用 google translate 的 api, 目前我使用以下脚本:
import requests
from urllib.parse import quote
import tempfile
import subprocess
import sys
import platform
import os
def play_word_audio(word):
# 编码单词并构建URL
encoded_word = quote(word)
url = f"https://translate.google.com.vn/translate_tts?ie=UTF-8&q={encoded_word}&tl=en&client=tw-ob"
# 设置浏览器头信息
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
temp_path = None # 初始化临时文件路径
try:
# 获取音频数据
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
# 创建临时文件
with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
temp_path = f.name
f.write(response.content)
# 根据系统选择不同的播放命令
if platform.system() == 'Windows':
subprocess.run(['mpv', '--no-terminal', temp_path], check=True)
else: # Linux/macOS
subprocess.run(['mpv', '--really-quiet', temp_path], check=True)
except requests.exceptions.RequestException as e:
print(f"网络错误: {e}")
except subprocess.CalledProcessError as e:
print(f"播放失败,请确认已安装mpv: {e}")
except Exception as e:
print(f"发生错误: {e}")
finally:
# 确保删除临时文件
if temp_path and os.path.exists(temp_path):
try:
os.remove(temp_path)
except Exception as e:
print(f"警告: 无法删除临时文件 {temp_path}: {e}")
if __name__ == "__main__":
if len(sys.argv) > 1:
word = sys.argv[1]
else:
word = input("请输入要发音的单词: ")
play_word_audio(word)