Python: 循環播放 英文單詞及其中文翻譯

加入好友
加入社群
Python: 循環播放 英文單詞及其中文翻譯 - 儲蓄保險王

code:

import pygame
from gtts import gTTS
import os
import time

# 初始化 pygame
pygame.mixer.init()

# 定義單詞列表
words = [
    {"english": "clarify", "chinese": "闡明"},
    {"english": "condition", "chinese": "條件"},
    {"english": "conflict resolution", "chinese": "衝突解決"},
    {"english": "consumer rights", "chinese": "消費者權益"},
    {"english": "cooling off period", "chinese": "冷靜期"},
    {"english": "defective", "chinese": "有缺陷的"},
    {"english": "disclose", "chinese": "披露"},
    {"english": "go the extra mile", "chinese": "付出更多努力"},
    {"english": "identical", "chinese": "完全相同的"},
    {"english": "last straw", "chinese": "最後一根稻草"},
    {"english": "opportunity", "chinese": "機會"},
    {"english": "perspective", "chinese": "觀點"},
    {"english": "point of view", "chinese": "觀點"},
    {"english": "prominent", "chinese": "顯著的"},
    {"english": "rule out", "chinese": "排除"},
    {"english": "store credit", "chinese": "購物抵用金"},
    {"english": "approve", "chinese": "批准"},
    {"english": "banner", "chinese": "橫幅"},
    {"english": "engage", "chinese": "雇用"},
    {"english": "jingle", "chinese": "廣告短曲"},
    {"english": "merchandising", "chinese": "商品推廣"},
    {"english": "prime time", "chinese": "黃金時段"},
    {"english": "prospect", "chinese": "前景"},
    {"english": "publicity", "chinese": "宣傳"},
    {"english": "rehearse", "chinese": "排練"},
    {"english": "reject", "chinese": "拒絕"},
    {"english": "slogan", "chinese": "標語"},
    {"english": "thorough", "chinese": "徹底的"},
    {"english": "upcoming", "chinese": "即將到來的"},
    {"english": "unfavorable", "chinese": "不利的"},
    {"english": "via", "chinese": "通過"}
]

# 定義音頻文件保存路徑
audio_dir = "audio_files"
if not os.path.exists(audio_dir):
    os.makedirs(audio_dir)

# 將單詞轉換為音頻文件
def generate_audio(word, language, filename):
    tts = gTTS(text=word, lang=language)
    filepath = os.path.join(audio_dir, filename)
    tts.save(filepath)
    return filepath

# 播放音頻文件
def play_audio(filepath):
    pygame.mixer.music.load(filepath)
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        time.sleep(0.1)

# 主程序循環播放英文和中文的發音
def main():
    print("開始播放單詞:")
    while True:  # 循環播放
        for word in words:
            english_word = word["english"]
            chinese_word = word["chinese"]

            # 生成英文發音
            english_audio = generate_audio(english_word, "en", f"{english_word}_en.mp3")
            # 生成中文翻譯發音
            chinese_audio = generate_audio(chinese_word, "zh", f"{english_word}_zh.mp3")

            # 播放英文發音
            print(f"正在播放英文:{english_word}")
            play_audio(english_audio)
            time.sleep(1)  # 間隔 1 

            # 播放中文翻譯
            print(f"正在播放中文翻譯:{chinese_word}")
            play_audio(chinese_audio)
            time.sleep(1)  # 間隔 1 

# 執行程序
if __name__ == "__main__":
    main()

code:

Python: 循環播放 英文單詞及其中文翻譯 - 儲蓄保險王

推薦hahow線上學習python: https://igrape.net/30afN

GUI介面(NB能跑,手機跑一點就報錯):

import pygame
from gtts import gTTS
import os
import time
import sys

# 初始化 pygame
pygame.init()
pygame.mixer.init()

# 設置顯示窗口大小
screen_width, screen_height = 480, 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('單詞學習')

# 定義顏色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 180, 0)
RED = (200, 0, 0)
GRAY = (200, 200, 200)

# 解決中文顯示問題
# 方法1嘗試加載系統字體
system_fonts = pygame.font.get_fonts()
chinese_font = None

# 嘗試找到支持中文的字體
potential_chinese_fonts = ['simsun', 'nsimsun', 'microsoftyahei', 'microsoftjhenghei', 'dfkaishu', 'arplumingcn']
for font_name in potential_chinese_fonts:
    if font_name in system_fonts:
        chinese_font = font_name
        break

# 如果找不到內建中文字體則嘗試加載系統字體文件
if chinese_font is None:
    font_paths = [
        # Windows 中文字體路徑
        "C:/Windows/Fonts/simsun.ttc",
        "C:/Windows/Fonts/msyh.ttc",
        # Linux 中文字體路徑
        "/usr/share/fonts/truetype/arphic/uming.ttc",
        # macOS 中文字體路徑
        "/System/Library/Fonts/PingFang.ttc",
        # Android 中文字體路徑 (Pydroid 相關)
        "/system/fonts/NotoSansCJK-Regular.ttc",
        "/system/fonts/DroidSansFallback.ttf"
    ]
    
    for path in font_paths:
        if os.path.exists(path):
            try:
                # 方法2直接加載字體文件
                font_large = pygame.font.Font(path, 36)
                font = pygame.font.Font(path, 28)
                font_small = pygame.font.Font(path, 24)
                print(f"已加載字體:{path}")
                break
            except:
                continue
    else:
        # 方法3如果以上方法都失敗使用默認字體並顯示英文
        print("警告:無法加載中文字體,將使用默認字體")
        font_large = pygame.font.SysFont(None, 36)
        font = pygame.font.SysFont(None, 28)
        font_small = pygame.font.SysFont(None, 24)
else:
    # 使用找到的中文字體
    font_large = pygame.font.SysFont(chinese_font, 36)
    font = pygame.font.SysFont(chinese_font, 28)
    font_small = pygame.font.SysFont(chinese_font, 24)
    print(f"已加載系統字體:{chinese_font}")

# 定義單詞列表
words = [
    {"english": "clarify", "chinese": "闡明"},
    {"english": "condition", "chinese": "條件"},
    {"english": "conflict resolution", "chinese": "衝突解決"},
    {"english": "consumer rights", "chinese": "消費者權益"},
    {"english": "cooling off period", "chinese": "冷靜期"},
    {"english": "defective", "chinese": "有缺陷的"},
    {"english": "reveal", "chinese": "揭示"},    
    {"english": "disclose", "chinese": "披露"},
    {"english": "enclose", "chinese": "放入封套"},
    {"english": "go the extra mile", "chinese": "付出更多努力"},
    {"english": "identical", "chinese": "完全相同的"},
    {"english": "last straw", "chinese": "最後一根稻草"},
    {"english": "opportunity", "chinese": "機會"},
    {"english": "perspective", "chinese": "觀點"},
    {"english": "point of view", "chinese": "觀點"},
    {"english": "permanent", "chinese": "永恆的"},
    {"english": "prominent", "chinese": "顯著的"},
    {"english": "rule out", "chinese": "排除"},
    {"english": "store credit", "chinese": "購物抵用金"},
    {"english": "approve", "chinese": "批准"},
    {"english": "banner", "chinese": "橫幅"},
    {"english": "engage", "chinese": "雇用"},
    {"english": "jingle", "chinese": "廣告短曲"},
    {"english": "merchandise", "chinese": "商品"},
    {"english": "merchandising", "chinese": "商品推廣"},
    {"english": "prime time", "chinese": "黃金時段"},
    {"english": "prospect", "chinese": "前景"},
    {"english": "publicity", "chinese": "宣傳"},
    {"english": "rehearse", "chinese": "排練"},
    {"english": "deny", "chinese": "否定"},
    {"english": "decline", "chinese": "拒絕"},
    {"english": "reject", "chinese": "拒絕"},
    {"english": "slogan", "chinese": "標語"},
    {"english": "thorough", "chinese": "徹底的"},
    {"english": "upcoming", "chinese": "即將到來的"},
    {"english": "unfavorable", "chinese": "不利的"},
    {"english": "via", "chinese": "通過"}
]

# 定義音頻文件保存路徑
audio_dir = "audio_files"
if not os.path.exists(audio_dir):
    os.makedirs(audio_dir)

# 翻譯英文文本為中文用於顯示按鈕文字
button_texts = {
    "上一個": "Previous",
    "播放": "Play",
    "下一個": "Next",
    "自動播放": "Auto Play",
    "退出": "Exit",
    "停止自動": "Stop Auto",
    "正在生成音頻檔案...": "Generating audio files...",
    "音頻檔案生成完成!": "Audio files generated!",
    "單詞": "Word",
    "操作說明:": "Instructions:",
    "點擊播放 - 播放當前單詞": "Click Play - Play current word",
    "上一個/下一個 - 切換單詞": "Previous/Next - Switch words",
    "自動播放 - 連續播放所有單詞": "Auto Play - Play all words continuously",
    "(點擊播放按鈕查看翻譯)": "(Click Play to see translation)"
}

# 定義按鈕類
class Button:
    def __init__(self, x, y, width, height, text, color=BLUE, hover_color=GREEN):
        self.rect = pygame.Rect(x, y, width, height)
        self.chinese_text = text
        self.english_text = button_texts.get(text, text)  # 獲取英文文本如果不存在就使用原文本
        self.color = color
        self.hover_color = hover_color
        self.current_color = color
        self.is_hovered = False

    def draw(self):
        # 繪製按鈕
        pygame.draw.rect(screen, self.current_color, self.rect, border_radius=10)
        pygame.draw.rect(screen, BLACK, self.rect, 2, border_radius=10)
        
        # 根據能否顯示中文決定顯示什麼文本
        try:
            # 嘗試渲染中文
            text_surface = font.render(self.chinese_text, True, WHITE)
            text_rect = text_surface.get_rect(center=self.rect.center)
            screen.blit(text_surface, text_rect)
        except:
            # 如果失敗渲染英文
            text_surface = font.render(self.english_text, True, WHITE)
            text_rect = text_surface.get_rect(center=self.rect.center)
            screen.blit(text_surface, text_rect)

    def is_clicked(self, pos):
        return self.rect.collidepoint(pos)

    def update(self, mouse_pos):
        # 更新按鈕顏色懸停效果
        if self.rect.collidepoint(mouse_pos):
            self.current_color = self.hover_color
            self.is_hovered = True
        else:
            self.current_color = self.color
            self.is_hovered = False

# 將單詞轉換為音頻文件
def generate_audio(word, language, filename):
    filepath = os.path.join(audio_dir, filename)
    if not os.path.exists(filepath):  # 只有在文件不存在時才生成
        tts = gTTS(text=word, lang=language)
        tts.save(filepath)
    return filepath

# 播放音頻文件
def play_audio(filepath):
    pygame.mixer.music.load(filepath)
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        pygame.time.Clock().tick(10)

# 在屏幕上顯示文字
def display_text(original_text, y_position, font_to_use=font, color=BLACK, center_x=None):
    # 獲取英文文本如果不存在就使用原文本
    english_text = button_texts.get(original_text, original_text)
    
    try:
        # 嘗試渲染中文
        text_surface = font_to_use.render(original_text, True, color)
    except:
        # 如果失敗渲染英文
        text_surface = font_to_use.render(english_text, True, color)
    
    if center_x is None:
        center_x = screen_width // 2
    text_rect = text_surface.get_rect(center=(center_x, y_position))
    screen.blit(text_surface, text_rect)

# 顯示加載進度
def show_loading_screen(progress, total):
    screen.fill(WHITE)
    display_text("正在生成音頻檔案...", 300, font_large, BLUE)
    display_text(f"{progress}/{total}", 350, font, BLUE)
    
    # 進度條
    progress_width = 300
    progress_height = 30
    outline_rect = pygame.Rect((screen_width - progress_width) // 2, 400, progress_width, progress_height)
    fill_width = int(progress_width * (progress / total))
    fill_rect = pygame.Rect((screen_width - progress_width) // 2, 400, fill_width, progress_height)
    
    pygame.draw.rect(screen, GREEN, fill_rect)
    pygame.draw.rect(screen, BLACK, outline_rect, 2)
    
    pygame.display.flip()

# 主程序
def main():
    current_index = 0
    show_chinese = False
    is_playing = False
    auto_play = False
    
    # 創建按鈕
    button_width = 120
    button_height = 60
    button_margin = 20
    
    prev_button = Button(30, screen_height - 100, button_width, button_height, "上一個", BLUE)
    play_button = Button((screen_width - button_width) // 2, screen_height - 100, button_width, button_height, "播放", GREEN)
    next_button = Button(screen_width - 30 - button_width, screen_height - 100, button_width, button_height, "下一個", BLUE)
    auto_button = Button((screen_width - button_width) // 2, screen_height - 180, button_width, button_height, "自動播放", RED)
    exit_button = Button(screen_width - 100, 30, 80, 40, "退出", RED)
    
    buttons = [prev_button, play_button, next_button, auto_button, exit_button]
    
    # 預先生成所有音頻文件
    print("正在生成音頻文件...")
    total_files = len(words) * 2
    progress = 0
    
    for word in words:
        # 更新加載進度
        show_loading_screen(progress, total_files)
        progress += 1
        
        generate_audio(word["english"], "en", f"{word['english']}_en.mp3")
        
        # 更新加載進度
        show_loading_screen(progress, total_files)
        progress += 1
        
        generate_audio(word["chinese"], "zh", f"{word['english']}_zh.mp3")
    
    print("音頻文件生成完成!")
    
    # 主循環
    running = True
    clock = pygame.time.Clock()
    last_auto_time = pygame.time.get_ticks()
    
    while running:
        current_time = pygame.time.get_ticks()
        mouse_pos = pygame.mouse.get_pos()
        
        # 處理自動播放
        if auto_play and not is_playing and current_time - last_auto_time > 3000:  # 3秒間隔
            is_playing = True
            show_chinese = True
            last_auto_time = current_time
            
            current_word = words[current_index]
            english_audio = os.path.join(audio_dir, f"{current_word['english']}_en.mp3")
            chinese_audio = os.path.join(audio_dir, f"{current_word['english']}_zh.mp3")
            
            play_audio(english_audio)
            time.sleep(0.8)
            play_audio(chinese_audio)
            
            # 播放完成後自動前進到下一個單詞
            current_index = (current_index + 1) % len(words)
            is_playing = False
        
        # 事件處理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:  # 左鍵點擊
                    for button in buttons:
                        if button.is_clicked(event.pos):
                            if button == play_button and not is_playing:
                                is_playing = True
                                show_chinese = True
                                
                                current_word = words[current_index]
                                english_audio = os.path.join(audio_dir, f"{current_word['english']}_en.mp3")
                                chinese_audio = os.path.join(audio_dir, f"{current_word['english']}_zh.mp3")
                                
                                play_audio(english_audio)
                                time.sleep(0.8)
                                play_audio(chinese_audio)
                                is_playing = False
                                
                            elif button == prev_button:
                                current_index = (current_index - 1) % len(words)
                                show_chinese = False
                                
                            elif button == next_button:
                                current_index = (current_index + 1) % len(words)
                                show_chinese = False
                                
                            elif button == auto_button:
                                auto_play = not auto_play
                                if auto_play:
                                    auto_button.chinese_text = "停止自動"
                                    auto_button.english_text = "Stop Auto"
                                    auto_button.color = GREEN
                                else:
                                    auto_button.chinese_text = "自動播放"
                                    auto_button.english_text = "Auto Play"
                                    auto_button.color = RED
                                
                            elif button == exit_button:
                                running = False
        
        # 更新界面
        screen.fill(WHITE)
        
        # 更新按鈕懸停狀態
        for button in buttons:
            button.update(mouse_pos)
        
        # 顯示當前單詞
        current_word = words[current_index]
        display_text(f"單詞 {current_index+1}/{len(words)}", 60, font, BLUE)
        
        # 英文單詞總是可以顯示
        eng_text_surface = font_large.render(current_word["english"], True, BLACK)
        eng_text_rect = eng_text_surface.get_rect(center=(screen_width // 2, 150))
        screen.blit(eng_text_surface, eng_text_rect)
        
        if show_chinese:
            display_text(current_word["chinese"], 220, font_large, BLACK)
        else:
            display_text("(點擊播放按鈕查看翻譯)", 220, font_small, GRAY)
        
        # 繪製按鈕
        for button in buttons:
            button.draw()
        
        # 顯示操作說明
        display_text("操作說明:", 400, font_small, BLACK)
        display_text("點擊播放 - 播放當前單詞", 440, font_small, BLACK)
        display_text("上一個/下一個 - 切換單詞", 480, font_small, BLACK)
        display_text("自動播放 - 連續播放所有單詞", 520, font_small, BLACK)
        
        pygame.display.flip()
        clock.tick(30)

# 執行程序
if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"錯誤: {e}")
    finally:
        pygame.quit()
        sys.exit()

推薦hahow線上學習python: https://igrape.net/30afN

跨平台兼容:

import pygame
from gtts import gTTS
import os
import time
import sys
import platform

# 初始化 pygame
pygame.init()
pygame.mixer.init()

# 設置顯示窗口大小
screen_width, screen_height = 480, 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Word Learning')

# 定義顏色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 180, 0)
RED = (200, 0, 0)
GRAY = (200, 200, 200)

# 檢測系統類型
system = platform.system()
print(f"Detected system: {system}")

# 確定是否在Android上運行
is_android = False
if hasattr(sys, 'getandroidapilevel'):
    is_android = True
    print("Running on Android")

# 根據不同系統加載合適的字體
chinese_font_loaded = False

try:
    if system == "Windows":
        # Windows中文字體
        potential_fonts = ["simsun.ttc", "msyh.ttc", "simhei.ttf"]
        for font_name in potential_fonts:
            font_path = os.path.join("C:/Windows/Fonts", font_name)
            if os.path.exists(font_path):
                font_large = pygame.font.Font(font_path, 42)
                font = pygame.font.Font(font_path, 32)
                font_small = pygame.font.Font(font_path, 24)
                chinese_font_loaded = True
                print(f"Loaded Windows font: {font_path}")
                break
    
    elif system == "Darwin":  # macOS
        # macOS中文字體
        font_path = "/System/Library/Fonts/PingFang.ttc"
        if os.path.exists(font_path):
            font_large = pygame.font.Font(font_path, 42)
            font = pygame.font.Font(font_path, 32)
            font_small = pygame.font.Font(font_path, 24)
            chinese_font_loaded = True
            print(f"Loaded macOS font: {font_path}")
    
    elif is_android:
        # Android中文字體
        android_fonts = [
            "/system/fonts/NotoSansCJK-Regular.ttc",
            "/system/fonts/DroidSansFallback.ttf"
        ]
        for font_path in android_fonts:
            if os.path.exists(font_path):
                font_large = pygame.font.Font(font_path, 42)
                font = pygame.font.Font(font_path, 32)
                font_small = pygame.font.Font(font_path, 24)
                chinese_font_loaded = True
                print(f"Loaded Android font: {font_path}")
                break
    
    elif system == "Linux":
        # Linux中文字體
        linux_fonts = [
            "/usr/share/fonts/truetype/arphic/uming.ttc",
            "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"
        ]
        for font_path in linux_fonts:
            if os.path.exists(font_path):
                font_large = pygame.font.Font(font_path, 42)
                font = pygame.font.Font(font_path, 32)
                font_small = pygame.font.Font(font_path, 24)
                chinese_font_loaded = True
                print(f"Loaded Linux font: {font_path}")
                break
except Exception as e:
    print(f"Error loading Chinese font: {e}")
    chinese_font_loaded = False

# 如果無法加載中文字體使用系統默認字體
if not chinese_font_loaded:
    print("Could not load Chinese font, using default font")
    font_large = pygame.font.SysFont(None, 42)
    font = pygame.font.SysFont(None, 32)
    font_small = pygame.font.SysFont(None, 24)

# 定義單詞列表
words = [
    {"english": "clarify", "chinese": "闡明"},
    {"english": "condition", "chinese": "條件"},
    {"english": "conflict resolution", "chinese": "衝突解決"},
    {"english": "consumer rights", "chinese": "消費者權益"},
    {"english": "cooling off period", "chinese": "冷靜期"},
    {"english": "defective", "chinese": "有缺陷的"},
    {"english": "disclose", "chinese": "披露"},
    {"english": "go the extra mile", "chinese": "付出更多努力"},
    {"english": "identical", "chinese": "完全相同的"},
    {"english": "last straw", "chinese": "最後一根稻草"},
    {"english": "opportunity", "chinese": "機會"},
    {"english": "perspective", "chinese": "觀點"},
    {"english": "Permanent", "chinese": "永恆的"},
    {"english": "prominent", "chinese": "顯著的"},
    {"english": "rule out", "chinese": "排除"},
    {"english": "store credit", "chinese": "購物抵用金"}
]

# 定義音頻文件保存路徑
audio_dir = "audio_files"
if not os.path.exists(audio_dir):
    os.makedirs(audio_dir)

# 定義中英文按鈕標籤
button_labels = {
    "prev": {"en": "PREV", "zh": "上一個"},
    "play": {"en": "PLAY", "zh": "播放"},
    "next": {"en": "NEXT", "zh": "下一個"},
    "auto": {"en": "AUTO", "zh": "自動播放"},
    "stop_auto": {"en": "STOP", "zh": "停止自動"},
    "exit": {"en": "EXIT", "zh": "退出"},
    "instructions": {"en": "Instructions:", "zh": "操作說明:"},
    "play_instruction": {"en": "PLAY - Play current word", "zh": "播放 - 播放當前單詞"},
    "nav_instruction": {"en": "PREV/NEXT - Change word", "zh": "上一個/下一個 - 切換單詞"},
    "auto_instruction": {"en": "AUTO - Play all words", "zh": "自動播放 - 連續播放所有單詞"},
    "click_to_see": {"en": "(Click PLAY to see translation)", "zh": "(點擊播放按鈕查看翻譯)"},
    "word_count": {"en": "Word", "zh": "單詞"},
    "generating": {"en": "Generating audio files...", "zh": "正在生成音頻檔案..."},
    "generated": {"en": "Audio files generated!", "zh": "音頻檔案生成完成!"}
}

# 定義按鈕類
class Button:
    def __init__(self, x, y, width, height, key, color=BLUE, hover_color=GREEN):
        self.rect = pygame.Rect(x, y, width, height)
        self.key = key
        self.color = color
        self.hover_color = hover_color
        self.current_color = color

    def draw(self):
        # 繪製按鈕
        pygame.draw.rect(screen, self.current_color, self.rect, border_radius=10)
        pygame.draw.rect(screen, BLACK, self.rect, 2, border_radius=10)
        
        # 根據是否支持中文選擇顯示文本
        lang = "zh" if chinese_font_loaded and not is_android else "en"
        text = button_labels[self.key][lang]
        
        text_surface = font.render(text, True, WHITE)
        text_rect = text_surface.get_rect(center=self.rect.center)
        screen.blit(text_surface, text_rect)

    def is_clicked(self, pos):
        return self.rect.collidepoint(pos)

    def update(self, mouse_pos):
        # 更新按鈕顏色懸停效果
        if self.rect.collidepoint(mouse_pos):
            self.current_color = self.hover_color
        else:
            self.current_color = self.color

# 將單詞轉換為音頻文件
def generate_audio(word, language, filename):
    filepath = os.path.join(audio_dir, filename)
    if not os.path.exists(filepath):  # 只有在文件不存在時才生成
        try:
            tts = gTTS(text=word, lang=language)
            tts.save(filepath)
            print(f"Generated: {filename}")
            return filepath
        except Exception as e:
            print(f"Error generating audio: {e}")
            return None
    return filepath

# 播放音頻文件
def play_audio(filepath):
    if filepath and os.path.exists(filepath):
        try:
            pygame.mixer.music.load(filepath)
            pygame.mixer.music.play()
            # 等待音頻播放完成但設置超時
            start_time = pygame.time.get_ticks()
            while pygame.mixer.music.get_busy():
                pygame.time.Clock().tick(10)
                # 如果播放超過5秒強制停止防止卡住
                if pygame.time.get_ticks() - start_time > 5000:
                    pygame.mixer.music.stop()
                    print("Audio timeout, stopped")
                    break
        except Exception as e:
            print(f"Error playing audio: {e}")

# 在屏幕上顯示文字
def display_text(key, y_position, font_to_use=font, color=BLACK, center_x=None, count=None):
    try:
        # 如果是帶有計數的文本
        if count is not None:
            lang = "zh" if chinese_font_loaded and not is_android else "en"
            base_text = button_labels[key][lang]
            text = f"{base_text} {count}"
        # 如果是普通的帶有翻譯的文本
        elif key in button_labels:
            lang = "zh" if chinese_font_loaded and not is_android else "en"
            text = button_labels[key][lang]
        # 如果是直接的文本
        else:
            text = key
        
        text_surface = font_to_use.render(text, True, color)
        if center_x is None:
            center_x = screen_width // 2
        text_rect = text_surface.get_rect(center=(center_x, y_position))
        screen.blit(text_surface, text_rect)
    except Exception as e:
        print(f"Error displaying text: {e}")

# 顯示加載進度
def show_loading_screen(progress, total):
    try:
        screen.fill(WHITE)
        display_text("generating", 300, font_large, BLUE)
        display_text(f"{progress}/{total}", 350, font, BLUE)
        
        # 進度條
        progress_width = 300
        progress_height = 30
        outline_rect = pygame.Rect((screen_width - progress_width) // 2, 400, progress_width, progress_height)
        fill_width = int(progress_width * (progress / total))
        fill_rect = pygame.Rect((screen_width - progress_width) // 2, 400, fill_width, progress_height)
        
        pygame.draw.rect(screen, GREEN, fill_rect)
        pygame.draw.rect(screen, BLACK, outline_rect, 2)
        
        pygame.display.flip()
    except Exception as e:
        print(f"Error showing loading screen: {e}")

# 主程序
def main():
    current_index = 0
    show_chinese = False
    is_playing = False
    auto_play = False
    
    # 創建按鈕
    button_width = 120
    button_height = 60
    
    prev_button = Button(30, screen_height - 100, button_width, button_height, "prev", BLUE)
    play_button = Button((screen_width - button_width) // 2, screen_height - 100, button_width, button_height, "play", GREEN)
    next_button = Button(screen_width - 30 - button_width, screen_height - 100, button_width, button_height, "next", BLUE)
    auto_button = Button((screen_width - button_width) // 2, screen_height - 180, button_width, button_height, "auto", RED)
    exit_button = Button(screen_width - 100, 30, 80, 40, "exit", RED)
    
    buttons = [prev_button, play_button, next_button, auto_button, exit_button]
    
    # 預先生成部分音頻文件
    print("Generating audio files...")
    total_files = min(10, len(words)) * 2  # 只為前10個單詞生成音頻
    progress = 0
    
    # 生成音頻文件
    audio_files = {}
    for i, word in enumerate(words):
        try:
            # 更新加載進度
            show_loading_screen(progress, total_files)
            progress += 1
            
            english_file = f"{word['english']}_en.mp3"
            english_path = generate_audio(word["english"], "en", english_file)
            audio_files[english_file] = english_path
            
            # 更新加載進度
            show_loading_screen(progress, total_files)
            progress += 1
            
            chinese_file = f"{word['english']}_zh.mp3"
            chinese_path = generate_audio(word["chinese"], "zh", chinese_file)
            audio_files[chinese_file] = chinese_path
            
            # 只生成前5個單詞的音頻其他的稍後按需生成
            if i >= 4:
                break
                
        except Exception as e:
            print(f"Error in generation: {e}")
    
    print("Initial audio files generated!")
    
    # 主循環
    running = True
    clock = pygame.time.Clock()
    last_auto_time = pygame.time.get_ticks()
    
    while running:
        try:
            current_time = pygame.time.get_ticks()
            mouse_pos = pygame.mouse.get_pos()
            
            # 處理自動播放
            if auto_play and not is_playing and current_time - last_auto_time > 3000:  # 3秒間隔
                is_playing = True
                show_chinese = True
                last_auto_time = current_time
                
                current_word = words[current_index]
                english_file = f"{current_word['english']}_en.mp3"
                chinese_file = f"{current_word['english']}_zh.mp3"
                
                # 確保音頻文件存在
                if english_file not in audio_files or not audio_files[english_file]:
                    audio_files[english_file] = generate_audio(current_word["english"], "en", english_file)
                    
                if chinese_file not in audio_files or not audio_files[chinese_file]:
                    audio_files[chinese_file] = generate_audio(current_word["chinese"], "zh", chinese_file)
                
                play_audio(audio_files[english_file])
                time.sleep(0.8)
                play_audio(audio_files[chinese_file])
                
                # 播放完成後自動前進到下一個單詞
                current_index = (current_index + 1) % len(words)
                is_playing = False
            
            # 事件處理
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:  # 左鍵點擊
                        for button in buttons:
                            if button.is_clicked(event.pos):
                                if button == play_button and not is_playing:
                                    is_playing = True
                                    show_chinese = True
                                    
                                    current_word = words[current_index]
                                    english_file = f"{current_word['english']}_en.mp3"
                                    chinese_file = f"{current_word['english']}_zh.mp3"
                                    
                                    # 確保音頻文件存在
                                    if english_file not in audio_files or not audio_files[english_file]:
                                        audio_files[english_file] = generate_audio(current_word["english"], "en", english_file)
                                        
                                    if chinese_file not in audio_files or not audio_files[chinese_file]:
                                        audio_files[chinese_file] = generate_audio(current_word["chinese"], "zh", chinese_file)
                                    
                                    play_audio(audio_files[english_file])
                                    time.sleep(0.8)
                                    play_audio(audio_files[chinese_file])
                                    is_playing = False
                                    
                                elif button == prev_button:
                                    current_index = (current_index - 1) % len(words)
                                    show_chinese = False
                                    
                                elif button == next_button:
                                    current_index = (current_index + 1) % len(words)
                                    show_chinese = False
                                    
                                elif button == auto_button:
                                    auto_play = not auto_play
                                    if auto_play:
                                        auto_button.key = "stop_auto"
                                        auto_button.color = GREEN
                                    else:
                                        auto_button.key = "auto"
                                        auto_button.color = RED
                                    
                                elif button == exit_button:
                                    running = False
            
            # 更新界面
            screen.fill(WHITE)
            
            # 更新按鈕懸停狀態
            for button in buttons:
                button.update(mouse_pos)
            
            # 顯示當前單詞
            current_word = words[current_index]
            display_text("word_count", 60, font, BLUE, None, f"{current_index+1}/{len(words)}")
            
            # 英文單詞直接顯示
            eng_text_surface = font_large.render(current_word["english"], True, BLACK)
            eng_text_rect = eng_text_surface.get_rect(center=(screen_width // 2, 150))
            screen.blit(eng_text_surface, eng_text_rect)
            
            # 中文翻譯只在需要時顯示
            if show_chinese:
                # 根據是否支持中文直接顯示或使用拼音
                if chinese_font_loaded:
                    chinese_text_surface = font_large.render(current_word["chinese"], True, BLACK)
                    chinese_text_rect = chinese_text_surface.get_rect(center=(screen_width // 2, 220))
                    screen.blit(chinese_text_surface, chinese_text_rect)
                else:
                    # 如果不支持中文顯示拼音版本
                    pinyin_mapping = {
                        "闡明": "Chan Ming",
                        "條件": "Tiao Jian",
                        "衝突解決": "Chong Tu Jie Jue",
                        "消費者權益": "Xiao Fei Zhe Quan Yi",
                        "冷靜期": "Leng Jing Qi",
                        "有缺陷的": "You Que Xian De",
                        "披露": "Pi Lu",
                        "付出更多努力": "Fu Chu Geng Duo Nu Li",
                        "完全相同的": "Wan Quan Xiang Tong De",
                        "最後一根稻草": "Zui Hou Yi Gen Dao Cao",
                        "機會": "Ji Hui",
                        "觀點": "Guan Dian",
                        "顯著的": "Xian Zhu De",
                        "排除": "Pai Chu",
                        "購物抵用金": "Gou Wu Di Yong Jin"
                    }
                    pinyin = pinyin_mapping.get(current_word["chinese"], current_word["chinese"])
                    pinyin_surface = font_large.render(pinyin, True, BLACK)
                    pinyin_rect = pinyin_surface.get_rect(center=(screen_width // 2, 220))
                    screen.blit(pinyin_surface, pinyin_rect)
            else:
                display_text("click_to_see", 220, font_small, GRAY)
            
            # 繪製按鈕
            for button in buttons:
                button.draw()
            
            # 顯示操作說明
            display_text("instructions", 400, font_small, BLACK)
            display_text("play_instruction", 440, font_small, BLACK)
            display_text("nav_instruction", 480, font_small, BLACK)
            display_text("auto_instruction", 520, font_small, BLACK)
            
            pygame.display.flip()
            clock.tick(30)
        
        except Exception as e:
            print(f"Error in main loop: {e}")
            time.sleep(1)

# 執行程序
if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"Program error: {e}")
    finally:
        try:
            pygame.quit()
        except:
            pass
        
        try:
            # 正常退出
            sys.exit()
        except:
            # 如果系統退出失敗使用os._exit
            try:
                import os
                os._exit(0)
            except:
                pass

推薦hahow線上學習python: https://igrape.net/30afN

Mastering TOEIC Skills (Unit 3,4) :

words = [
    {"english": "parcel", "chinese": "包裹"},
    {"english": "package", "chinese": "包裹"},
    {"english": "loading area", "chinese": "裝載區"},
    {"english": "express delivery", "chinese": "快遞"},
    {"english": "declare", "chinese": "申報"},
    {"english": "harbor", "chinese": "港口"},
    {"english": "cargo plane", "chinese": "貨機"},
    {"english": "shipping agent", "chinese": "貨運代理"},
    {"english": "container", "chinese": "貨櫃"},
    {"english": "in transit", "chinese": "運輸中"},
    {"english": "weight limit", "chinese": "重量限制"},
    {"english": "bulk", "chinese": "散裝"},
    {"english": "shipments", "chinese": "貨運"},
    {"english": "tracking number", "chinese": "追蹤號碼"},
    {"english": "container ship", "chinese": "貨櫃船"},
    {"english": "cargo", "chinese": "貨物"},
    {"english": "economy", "chinese": "經濟"},
    {"english": "export", "chinese": "出口"},
    {"english": "import", "chinese": "進口"},
    {"english": "import duty", "chinese": "進口稅"},
    {"english": "lightweight", "chinese": "輕量的"},
    {"english": "logistics", "chinese": "物流"},
    {"english": "merchandise", "chinese": "商品"},
    {"english": "quota", "chinese": "配額"},
    {"english": "reference", "chinese": "參考"},
    {"english": "surcharge", "chinese": "附加費"},
    {"english": "tariff", "chinese": "關稅"},
    {"english": "time-sensitive", "chinese": "時間敏感的"},
    {"english": "time zone", "chinese": "時區"},
    {"english": "trade barrier", "chinese": "貿易壁壘"},
    {"english": "consecutive", "chinese": "連續的"},
    {"english": "recession", "chinese": "經濟衰退"},
    {"english": "cash-strapped", "chinese": "資金緊張的"},
    {"english": "balance sheet", "chinese": "資產負債表"},
    {"english": "penalty", "chinese": "懲罰"},
    {"english": "fluctuates", "chinese": "波動"},
    {"english": "subtract", "chinese": "減去"},
    {"english": "funding", "chinese": "資金"},
    {"english": "accrue", "chinese": "累積"},
    {"english": "volatile", "chinese": "不穩定的"},
    {"english": "transfer", "chinese": "轉移"},
    {"english": "secure", "chinese": "安全的"},
    {"english": "price hikes", "chinese": "價格上漲"},
    {"english": "outweigh", "chinese": "超過"},
    {"english": "allot", "chinese": "分配"},
    {"english": "assets", "chinese": "資產"},
    {"english": "boost", "chinese": "促進"},
    {"english": "cash flow", "chinese": "現金流"},
    {"english": "earnings", "chinese": "收益"},
    {"english": "enterprise", "chinese": "企業"},
    {"english": "exempt", "chinese": "免除的"},
    {"english": "gross income", "chinese": "總收入"},
    {"english": "intervene", "chinese": "干預"},
    {"english": "net worth", "chinese": "淨資產"},
    {"english": "ongoing", "chinese": "持續的"},
    {"english": "payroll", "chinese": "薪資名單"},
    {"english": "profitable", "chinese": "有利可圖的"},
    {"english": "repossess", "chinese": "收回"},
    {"english": "return", "chinese": "收益"}
]

推薦hahow線上學習python: https://igrape.net/30afN

加入好友
加入社群
Python: 循環播放 英文單詞及其中文翻譯 - 儲蓄保險王

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡

You may also like...

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *