diff --git "a/Voice_Story_Player.py" "b/Voice_Story_Player.py" new file mode 100644--- /dev/null +++ "b/Voice_Story_Player.py" @@ -0,0 +1,1934 @@ +import tkinter as tk +from tkinter import messagebox, colorchooser, font as tkfont, filedialog, simpledialog +from PIL import Image, ImageTk, ImageSequence +import cv2 +import os +import pygame +import re +from tkinterdnd2 import TkinterDnD, DND_FILES +import subprocess +import random +import threading +import ctypes +import time +import json +import chardet +import shutil +from send2trash import send2trash +import numpy as np +user32 = ctypes.windll.user32 + +class VoiceStoryPlayer(TkinterDnD.Tk): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.screen_width = user32.GetSystemMetrics(0) or 1920 # 画面の幅を取得 + self.screen_height = user32.GetSystemMetrics(1) or 1080 # 画面の高さを取得 + window_width = 1010 + window_height = 730 + self.canvas_width = 480 + self.canvas_height = self.canvas_width + play_window_width = 1200 + play_window_height = 900 + self.current_size = 1200, 900 + self.display_text = None + self.title("Voice Story Player") + self.resizable(False, False) + self.py_folder = os.path.abspath(os.path.dirname(__file__)).replace('\\', '/') + self.save_setting_path = os.path.join(self.py_folder, "SETTING.txt").replace('\\', '/') + self.json_path = os.path.join(self.py_folder, "CHARACTER_DATA.json").replace('\\', '/') + self.stories_path = os.path.join(self.py_folder, "STORIES").replace('\\', '/') + if not os.path.exists(self.stories_path): + os.mkdir(self.stories_path) + pygame.mixer.init() + self.hwnd = ctypes.windll.kernel32.GetConsoleWindow() + if self.hwnd: + ctypes.windll.user32.ShowWindow(self.hwnd, 0) # SW_HIDE: ウィンドウを完全非表示 + print("ターミナルを最小化します。") + # variablle to save + self.window_geometry = f"{window_width}x{window_height}+{(self.screen_width - window_width) // 2}+{(self.screen_height - window_height) // 2}" + self.play_window_geometry = f"{play_window_width}x{play_window_height}+0+0" + self.full_screen = False + self.voice_interval = 800 + self.line_break = 20 + self.sec_per_char = 100 + self.default_bgm = True + self.adjust_font_size = True + self.punctuation_marks = "。、!?・‥….,!?ー~」』】]))" + self.volume = 50 + + self.character_list = [{"name": "DEFAULT", "font": "メイリオ", "size": 30, "style": "normal", "color": "black", "color2": "white", "edge":3, "position": 10}] + + self.load_setting() + self.load_character_data() + plot = self.window_geometry.split("+") + x, y = plot[1], plot[2] + self.geometry(f"{window_width}x{window_height}+{x}+{y}") + + self.story_list = [] + self.current_story_index = 0 + self.total_story_num = 0 + self.story_txt_path = "" + self.story_name = "" + self.cut_list = [] + self.cut_index = 0 + self.total_cut_num = [] + self.playing = False + self.interruption = False + self.skip_voice = False + self.music_title = "" + self.bgm = "" + self.cut_modification = False + self.forbidden_chars_display = '< > : " / \\ | ? *' + self.sound_effect_list = [ + "C:/Windows/Media/Alarm02.wav", "C:/Windows/Media/Windows Logoff Sound.wav", "C:/Windows/Media/Windows Exclamation.wav", "C:/Windows/Media/Ring06.wav", "C:/Windows/Media/notify.wav", + "C:/Windows/Media/Speech On.wav", "C:/Windows/Media/Windows Notify System Generic.wav", "C:/Windows/Media/Speech Sleep.wav", "C:/Windows/Media/Windows Pop-up Blocked.wav", "C:/Windows/Media/Windows Hardware Insert.wav", + "C:/Windows/Media/Windows Notify Calendar.wav", "C:/Windows/Media/Windows Message Nudge.wav", "C:/Windows/Media/Windows Foreground.wav", "C:/Windows/Media/chord.wav", "C:/Windows/Media/Ring06.wav"] + self.edge_plot = [ + [(-1, -1), (1, -1), (-1, 1), (1, 1), (0, -1), (-1, 0), (0, 1), (1, 0)], + [(-2, -2), (2, -2), (-2, 2), (2, 2), (0, -2), (-2, 0), (0, 2), (2, 0)], + [(-4, -4), (4, -4), (-4, 4), (4, 4), (0, -4), (-4, 0), (0, 4), (4, 0), (-2, 4), (2, 4), (-4, 2), (4, 2), (-4, -2), (4, -2), (-2, -4), (2, -4)], + [(4, 4), (3, 3), (2, 2), (1, 1)], + [(8, 8), (7, 7), (6, 6),(5, 5), (4, 4), (3, 3), (2, 2), (1, 1)], + [(16, 16), (15, 15), (14, 14), (13, 13), (12, 12), (11, 11), (10, 10), (9, 9), (8, 8), (7, 7), (6, 6), (5, 5), (4, 4), (3, 3), (2, 2), (1, 1)], + ] + +# ------ Basic Window ------- + + # ストーリーフレーム + self.story_frame = tk.Frame(self, bg="lightblue") + self.story_frame.grid(row= 0, column= 0, padx= 5, pady= 5, sticky="news") + # ストーリーインデックス + self.current_story_index_frame = tk.Frame(self.story_frame, bg="navy") + self.current_story_index_frame.grid(row= 0, column= 0, padx= 10, pady= 5, sticky="ew") + tk.Label(self.current_story_index_frame, text="STORY", bg="navy", fg="white", font=("Arial Black", 25, "bold"), justify="left").grid(row=0, column=0, sticky="w") + self.current_story_index_frame.grid_columnconfigure(1, weight=1) + self.current_story_index_label = tk.Label(self.current_story_index_frame, bg="navy", fg="white", font=("Arial Black", 25, "bold"), justify="right") + self.current_story_index_label.grid(row=0, column=2, sticky="e") + # ストーリー名 + self.story_name_label = tk.Label(self.story_frame, bg="lightblue", font=("メイリオ", 25, "bold"), justify="left", width= 21, height= 4) + self.story_name_label.grid(row=1, column=0, padx= 10, pady= 5, sticky="w") + # ストーリーボタンフレーム + story_button_frame = tk.Frame(self.story_frame, bg="navy") + story_button_frame.grid(row= 6, column= 0, padx= 5, pady= 5, sticky="ew") + self.play_mode_button = tk.Button(story_button_frame, font=("Arial", 10, "bold"), command=lambda: self.select_play_mode(), width=16, fg="white") + self.play_mode_button.grid(row=3, column=1, padx=10, pady=5, sticky="w") + story_select_button = tk.Button(story_button_frame, text="ストーリー選択", font=("Arial", 15, "bold"), command=lambda: self.select_story(reload=False), bg="blue", fg="yellow") + story_select_button.grid(row=3, column=2, padx=10, pady=5, sticky="e") + story_add_button = tk.Button(story_button_frame, text="追加", font=("Arial", 15, "bold"), command=lambda: self.add_story(), bg="green", fg="white") + story_add_button.grid(row=3, column=3, padx=10, pady=5, sticky="e") + story_del_button = tk.Button(story_button_frame, text="削除", font=("Arial", 10, "bold"), command=lambda: self.delete_story_txt(), bg="red", fg="white") + story_del_button.grid(row=3, column=4, padx=10, pady=5, sticky="e") + + # カットフレーム + self.cut_frame = tk.Frame(self, bg="aquamarine") + self.cut_frame.grid(row= 1, column= 0, padx= 5, pady= 5, sticky="news") + # Image + self.image_button_frame = tk.Frame(self.cut_frame, bg="dark green") + self.image_button_frame.grid(row= 0, column= 0, padx= 5, pady= 5, sticky="ew") + tk.Label(self.image_button_frame, text="IMAGE", bg="dark green", fg="white", font=("Arial Black", 20, "bold"), justify="left").grid(row=0, column=0, sticky="w") + self.image_button_frame.grid_columnconfigure(1, weight=1) + image_button = tk.Button(self.image_button_frame, text="イメージ選択", font=("Arial", 13, "bold"), command=lambda: self.select_path(0), bg="blue", fg="yellow") + image_button.grid(row=0, column=2, padx=10, pady=5, sticky="e") + image_reset_button = tk.Button(self.image_button_frame, text="削除", font=("Arial", 10, "bold"), command=lambda:self.delete_path(0), bg="orange", fg="white") + image_reset_button.grid(row=0, column=3, padx=10, pady=5, sticky="e") + self.image_path_label = tk.Label(self.cut_frame, bg="white", font=("Helvetica", 10, "bold"), justify="left", anchor="nw", width= 58, wraplength=450, height=2) + self.image_path_label.grid(row=1, column=0, padx= 10, pady= 5, sticky="w") + self.image_path_label.bind("", lambda event: self.open_folder_in_explorer(self.cut_list[self.current_story_index][self.cut_index][0], event)) + # Voice + self.voice_button_frame = tk.Frame(self.cut_frame, bg="dark green") + self.voice_button_frame.grid(row= 2, column= 0, padx= 5, pady= 5, sticky="ew") + tk.Label(self.voice_button_frame, text="VOICE", bg="dark green", fg="white", font=("Arial Black", 20, "bold"), justify="left").grid(row=0, column=0, sticky="w") + self.voice_button_frame.grid_columnconfigure(1, weight=1) + voice_select_button = tk.Button(self.voice_button_frame, text="声フォルダ選択", font=("Arial", 13, "bold"), command=lambda:self.select_path(1), bg="blue", fg="yellow") + voice_select_button.grid(row=0, column=2, padx=10, pady=5, sticky="e") + text_edit_button = tk.Button(self.voice_button_frame, text="txt編集", font=("Arial", 13, "bold"), command=lambda:self.edit_text(), bg="blue", fg="yellow") + text_edit_button.grid(row=0, column=3, padx=10, pady=5, sticky="e") + voice_reset_button = tk.Button(self.voice_button_frame, text="削除", font=("Arial", 10, "bold"), command=lambda:self.delete_path(1), bg="orange", fg="white") + voice_reset_button.grid(row=0, column=4, padx=10, pady=5, sticky="e") + self.voice_path_label = tk.Label(self.cut_frame, bg="white", font=("Helvetica", 10, "bold"), justify="left", anchor="nw", width= 58, wraplength=450, height=2) + self.voice_path_label.grid(row=3, column=0, padx= 10, pady= 5, sticky="w") + self.voice_path_label.bind("", lambda event: self.open_folder_in_explorer(self.cut_list[self.current_story_index][self.cut_index][1], event)) + # BGM + self.bgm_button_frame = tk.Frame(self.cut_frame, bg="dark green") + self.bgm_button_frame.grid(row= 4, column= 0, padx= 5, pady= 5, sticky="ew") + tk.Label(self.bgm_button_frame, text="BGM", bg="dark green", fg="white", font=("Arial Black", 20, "bold"), justify="left").grid(row=0, column=0, sticky="w") + self.bgm_button_frame.grid_columnconfigure(1, weight=1) + bgm_select_button = tk.Button(self.bgm_button_frame, text="BGM選択", font=("Arial", 13, "bold"), command=lambda:self.select_path(2), bg="blue", fg="yellow") + bgm_select_button.grid(row=0, column=1, padx=10, pady=5, sticky="e") + bgm_no_button = tk.Button(self.bgm_button_frame, text="無音", font=("Arial", 13, "bold"), command=lambda:self.no_bgm(), bg="blue", fg="yellow") + bgm_no_button.grid(row=0, column=2, padx=10, pady=5, sticky="e") + bgm_reset_button = tk.Button(self.bgm_button_frame, text="削除", font=("Arial", 10, "bold"), command=lambda:self.delete_path(2), bg="orange", fg="white") + bgm_reset_button.grid(row=0, column=3, padx=10, pady=5, sticky="e") + self.bgm_path_label = tk.Label(self.cut_frame, bg="white", font=("Helvetica", 10, "bold"), justify="left", anchor="nw", width= 58, wraplength=450, height=2) + self.bgm_path_label.grid(row=5, column=0, padx= 10, pady= 5, sticky="w") + self.bgm_path_label.bind("", lambda event: self.open_folder_in_explorer(self.cut_list[self.current_story_index][self.cut_index][2], event)) + + # カットボタンフレーム + cut_button_frame = tk.Frame(self.cut_frame, bg="dark green") + cut_button_frame.grid(row= 6, column= 0, padx= 5, pady= 5, sticky="ew") + cut_add_button = tk.Button(cut_button_frame, text="カット移動", font=("Arial", 15, "bold"), command=lambda: self.move_cut(), bg="gold") + cut_add_button.grid(row=0, column=0, padx=10, pady=5, sticky="w") + cut_divide_button = tk.Button(cut_button_frame, text="分割", font=("Arial", 15, "bold"), command=lambda: self.cut_divide(), bg="gold") + cut_divide_button.grid(row=0, column=1, padx=10, pady=5, sticky="w") + cut_button_frame.grid_columnconfigure(2, weight=1) + cut_add_button = tk.Button(cut_button_frame, text="追加", font=("Arial", 15, "bold"), command=lambda: self.add_cut(), bg="green", fg="white") + cut_add_button.grid(row=0, column=3, padx=10, pady=5, sticky="e") + cut_del_button = tk.Button(cut_button_frame, text="削除", font=("Arial", 10, "bold"), command=lambda: self.delete_cut(), bg="red", fg="white") + cut_del_button.grid(row=0, column=4, padx=10, pady=5, sticky="e") + + # プレイヤーフレーム + self.player_frame = tk.Frame(self, bg="lemon chiffon", width = self.canvas_width + 10) + self.player_frame.grid(row= 0, rowspan=2, column= 1, padx= 5, pady= 5, sticky="news") + # カットインデックス + self.cut_index_frame = tk.Frame(self.player_frame, bg="orange3") + self.cut_index_frame.grid(row= 0, column= 0, padx= 10, pady= 5, sticky="ew") + tk.Label(self.cut_index_frame, text="CUT # ", bg="orange3", fg="white", font=("Arial Black", 25, "bold"), justify="left").grid(row=0, column=0, sticky="w") + self.cut_index_frame.grid_columnconfigure(1, weight=1) + self.cut_index_label = tk.Label(self.cut_index_frame, text=f"{self.cut_index}/{self.total_cut_num}", bg="orange3", fg="white", font=("Arial Black", 25, "bold"), justify="right") + self.cut_index_label.grid(row=0, column=2, sticky="e") + # 画像表示 + self.canvas_frame = tk.Frame(self.player_frame, bg="lemon chiffon") + self.canvas_frame.grid(row= 1, column= 0, padx=10, pady=5, sticky="news") + self.image_canvas = tk.Canvas(self.canvas_frame, bg="black", highlightthickness=0, bd=0, width= self.canvas_width, height= self.canvas_height) + self.image_canvas.grid(row=0, column=0, sticky="news") + # 操作ボタンフレーム + operation_button_frame = tk.Frame(self.player_frame, bg="orange3") + operation_button_frame.grid(row= 2, column= 0, padx= 10, pady= 5, sticky="sew") + head_cut_button = tk.Button(operation_button_frame, text="|◀", font=("Arial", 15), command=lambda:self.seek_cut_button(-1000), bg="blue", fg="white") + head_cut_button.grid(row= 0, column= 0, padx= 5, pady= 5, sticky="w") + minus_5_button = tk.Button(operation_button_frame, text="◀ 5", font=("Arial", 15), command=lambda:self.seek_cut_button(-5), bg="blue", fg="white") + minus_5_button.grid(row= 0, column= 1, padx= 5, pady= 5, sticky="w") + previous_button = tk.Button(operation_button_frame, text=" ◀ ", font=("Arial", 15), command=lambda:self.seek_cut_button(-1), bg="blue", fg="white") + previous_button.grid(row= 0, column= 2, padx= 5, pady= 5, sticky="w") + operation_button_frame.grid_columnconfigure(3, weight=1) + play_story_button = tk.Button(operation_button_frame, text=" PLAY ", font=("Arial Black", 20), command=lambda:self.display_play_window(), bg="yellow", fg="red") + play_story_button.grid(row= 0, column= 4, padx= 5, pady= 5) + operation_button_frame.grid_columnconfigure(5, weight=1) + next_button = tk.Button(operation_button_frame, text=" ▶ ", font=("Arial", 15), command=lambda:self.seek_cut_button(1), bg="blue", fg="white") + next_button.grid(row= 0, column= 6, padx= 5, pady= 5, sticky="e") + plus_5_button = tk.Button(operation_button_frame, text="5 ▶", font=("Arial", 15), command=lambda:self.seek_cut_button(5), bg="blue", fg="white") + plus_5_button.grid(row= 0, column= 7, padx= 5, pady= 5, sticky="e") + last_cut_button = tk.Button(operation_button_frame, text="▶|", font=("Arial", 15), command=lambda:self.seek_cut_button(1000), bg="blue", fg="white") + last_cut_button.grid(row= 0, column= 8, padx= 5, pady= 5, sticky="e") + + # オプションフレーム + setting_frame = tk.Frame(self.player_frame, bg="peach puff") + setting_frame.grid(row= 3, column= 0, padx= 10, pady= 5, sticky="news") + + tk.Button(setting_frame, text="キャラクター セリフ表示設定", font=("メイリオ", 13, "bold"), command=lambda:self.open_character_settings_window(), bg="gold3", fg="white").grid(row=0, column=0, padx=30, pady=10, sticky="e") + setting_frame.grid_columnconfigure(1, weight=1) + tk.Button(setting_frame, text="再生設定", font=("メイリオ", 13, "bold"), command=lambda:self.open_settings_window(), bg="gold3", fg="white").grid(row=0, column=2, padx=30, pady=10, sticky="e") + + self.drop_target_register(DND_FILES) + self.dnd_bind('<>', lambda e: self.on_drop(e)) + self.story_name_label.bind("", lambda event: self.select_story_wheel(event)) + self.image_canvas.bind("", lambda event: self.select_cut_wheel(event)) + self.image_canvas.bind("", lambda event=None: self.display_play_window()) + self.story_name_label.bind("", lambda event=None: self.select_story(reload=False)) + self.protocol("WM_DELETE_WINDOW", lambda event=None:self.on_close()) + + self.load_story_and_cut_data() + self.refresh_display_all() + self.sound_effect(0) + +# ------ Load and Save Setting ------- + + def load_setting(self): + if os.path.exists(self.save_setting_path): + try: + with open(self.save_setting_path, 'r', encoding='utf-8') as file: + text = file.read().strip() + print(f"Setting Loaded:\n{text}") + lines = text.splitlines() + self.window_geometry = lines[0] + self.play_window_geometry = lines[1] + self.full_screen = lines[2] == "True" + self.voice_interval = int(lines[3]) + self.line_break = int(lines[4]) + self.sec_per_char = int(lines[5]) + self.default_bgm = lines[6] == "True" + self.adjust_font_size = lines[7] == "True" + self.punctuation_marks = lines[8] + self.volume = int(lines[9]) + except Exception as e: + messagebox.showinfo("エラー", str(e), parent=self) + print(str(e)) + return + + def save_setting(self): + """設定ファイルを保存する""" + save_text = "\n".join([ + self.window_geometry, + self.play_window_geometry, + str(self.full_screen), + str(self.voice_interval), + str(self.line_break), + str(self.sec_per_char), + str(self.default_bgm), + str(self.adjust_font_size), + self.punctuation_marks, + str(self.volume), + ]) + try: + with open(self.save_setting_path, 'w', encoding='utf-8') as file: + file.write(save_text) + print("Setting Saved:\n", save_text) + except Exception as e: + messagebox.showinfo("エラー", str(e), parent=self) + print(str(e)) + + def load_character_data(self): + if not os.path.exists(self.json_path): + return + with open(self.json_path, "r", encoding="utf-8") as file: + self.character_list = json.load(file) + +# ------ Load Story Data ------- + + def load_story_and_cut_data(self): + self.get_story_list() + total_num_of_list = len(self.story_list) + if total_num_of_list: + self.play_mode = [0] * total_num_of_list + self.random_image_folder = [""] * total_num_of_list + self.random_voice_num = [3] * total_num_of_list + self.random = [True] * total_num_of_list + self.min_display = [5] * total_num_of_list + for i in range (self.total_story_num): + self.cut_list.append([]) + self.get_cut_data(i) + + def get_story_list(self): + self.story_list = [ + os.path.join(self.stories_path, file_name).replace('\\', '/') + for file_name in os.listdir(self.stories_path) + if file_name.endswith(".txt") + ] + self.story_list = sorted(self.story_list, key=lambda path: os.path.basename(path)) + if self.story_list: + self.total_story_num = len(self.story_list) + else: + self.total_story_num = 0 + print("Load Story List:\n", self.story_list) + + def get_cut_data(self, story_index): + self.cut_index = 0 + self.cut_list[story_index] = [] + filepath = self.story_list[story_index] + if not os.path.exists(filepath): + print(f"File not found: {filepath}") + return + try: + with open(filepath, 'r', encoding='utf-8') as file: + text = file.read() + except Exception as e: + messagebox.showinfo("エラー", str(e), parent=self) + print(str(e)) + return + lines = text.splitlines() + if lines: + first_line = lines[0] + if first_line: + try: + first_char, first_line = first_line[0], first_line[1:] + if first_char == "*": + story_data = first_line.split("*") + self.play_mode[story_index] = int(story_data[0]) + self.random_image_folder[story_index] = story_data[1] + self.random_voice_num[story_index] = int(story_data[2]) + self.random[story_index] = story_data[3] == "True" + self.min_display[story_index] = float(story_data[4]) + lines.pop(0) + except Exception as e: + print(str(e)) + for i, line in enumerate(lines): + line = line.strip() + if not line: + continue + else: + cut_data = line.split("|") + while len(self.cut_list[story_index]) <= i: + self.cut_list[story_index].append([]) + self.cut_list[story_index][i] = cut_data + + def save_cutdata_to_story_txt(self): + if self.cut_modification and os.path.exists(self.story_txt_path): + a = str(self.play_mode[self.current_story_index]) + b = self.random_image_folder[self.current_story_index] + c = str(self.random_voice_num[self.current_story_index]) + d = str(self.random[self.current_story_index]) + e = str(self.min_display[self.current_story_index]) + save_text = f"*{a}*{b}*{c}*{d}*{e}\n" + for list in self.cut_list[self.current_story_index]: + add_text = f"{list[0]}|{list[1]}|{list[2]}\n" + save_text += add_text + save_text = save_text.rstrip('\n') + with open(self.story_txt_path, 'w', encoding='utf-8') as f: + f.write(save_text) + self.cut_modification = False + +# ------ Display Data ------- + + def refresh_display_all(self): + if self.story_list: + self.current_story_index_label.config(text=f"{self.current_story_index + 1} / {self.total_story_num}") + self.story_txt_path = self.story_list[self.current_story_index] + self.story_name = os.path.splitext(os.path.basename(self.story_txt_path))[0] + self.story_name_label.config(text= self.story_name.replace(' ', '\n')) + self.show_playmode_button() + else: + self.story_txt_path = None + self.current_story_index_label.config(text="None/None") + self.story_name_label.config(text= "ストーリーがありません。\n追加ボタンから\n新規作成して下さい。") + self.display_cut_data() + + def display_cut_data(self): + self.display_cut_index() + self.refresh_cut_path() + self.display_cut_image() + + def display_cut_index(self): + if self.cut_list and 0 <= self.current_story_index < len(self.cut_list): + if self.cut_list[self.current_story_index] and 0 <= self.cut_index < len(self.cut_list[self.current_story_index]): + if self.cut_list[self.current_story_index][self.cut_index]: + self.total_cut_num = len(self.cut_list[self.current_story_index]) + self.cut_index = max(min(self.cut_index, self.total_cut_num - 1), 0) + else: + self.total_cut_num = 0 + self.cut_index = 0 + self.cut_index_label.config(text= f"{self.cut_index + 1} / {self.total_cut_num}") + + def refresh_cut_path(self): + path = [""] * 3 + char_color = ["black"] * 3 + if self.cut_list[self.current_story_index][self.cut_index]: + for i in range(3): + path[i] = self.cut_list[self.current_story_index][self.cut_index][i] + if path[i] : + if not os.path.exists(path[i]): + char_color[i] = "red" + if i == 0: + img_filename = os.path.basename(path[0]) + voice_folder_path = os.path.dirname(self.cut_list[self.current_story_index][0][1]) + new_img_path = os.path.join(voice_folder_path, img_filename).replace('\\', '/') + if os.path.exists(new_img_path): + self.cut_list[self.current_story_index][self.cut_index][0] = new_img_path + path[0] = new_img_path + char_color[0] = "black" + elif i == 1: + voice_folder_name = os.path.basename(path[1]) + cut_1_voice__path = os.path.dirname(self.cut_list[self.current_story_index][0][1]) + new_voice_folder_path = os.path.join(cut_1_voice__path, voice_folder_name).replace('\\', '/') + if os.path.exists(new_voice_folder_path): + self.cut_list[self.current_story_index][self.cut_index][1] = new_voice_folder_path + path[1] = new_voice_folder_path + char_color[1] = "black" + elif (i == 2 and path[i] == "NO"): + char_color[i] = "black" + self.image_path_label.config(text = path[0], fg = char_color[0]) + self.voice_path_label.config(text = path[1], fg = char_color[1]) + self.bgm_path_label.config(text = path[2], fg = char_color[2]) + + def display_cut_image(self): + self.image_canvas.delete("all") + path = self.cut_list[self.current_story_index][self.cut_index][0] + if not (path and os.path.exists(path)): + return + _, extension = os.path.splitext(path) + if extension in ('.mp4', '.webm'): + image = self.get_first_frame_from_video(path) + else: + image = self.get_display_image(path) + if image: + image.thumbnail((self.canvas_width, self.canvas_height), Image.LANCZOS) + resize_width, resize_height = image.size + x_center = (self.canvas_width - resize_width) // 2 + y_center = (self.canvas_height - resize_height) // 2 + tk_image = ImageTk.PhotoImage(image) + self.image_canvas.create_image(x_center, y_center, anchor="nw", image=tk_image) + self.image_canvas.image = tk_image # メモリリーク防止のため参照を保持 + + def get_first_frame_from_video(self, video_path): + # 動画ファイルを読み込む + cap = cv2.VideoCapture(video_path) + # 最初のフレームを読み取る + ret, frame = cap.read() + if ret: + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + img = Image.fromarray(frame_rgb) + cap.release() # 必要なフレームを取得後、リソースを解放 + return img + else: + print("動画の最初のフレームを取得できませんでした。") + cap.release() # エラー時にもリソースを解放 + return None + + def get_display_image(self, image_path): + # 画像を開く + img = Image.open(image_path) + # フォーマットによって処理を分ける + if img.format in ('GIF', 'WEBP'): + img.seek(0) # 最初のフレームに移動 + display_image = img.copy() + else: + display_image = img + return display_image + +# ------ Function ------- + + def on_drop(self, event, ): + if not self.story_list: + self.add_story() + return + dropped_path = event.data.strip("{}") + path = os.path.abspath(dropped_path).replace('\\', '/') + _, extension = os.path.splitext(path) + if extension in ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.mp4', '.webm'): + self.cut_list[self.current_story_index][self.cut_index][0] = path + elif extension in ('.mp3', '.wav'): + self.cut_list[self.current_story_index][self.cut_index][2] = path + elif os.path.isdir(path): + self.cut_list[self.current_story_index][self.cut_index][1] = path + else: + self.sound_effect(12) + return + self.sound_effect(11) + self.display_cut_data() + self.cut_modification = True + + def open_folder_in_explorer(self, path, event=None): + if os.path.isdir(path): + os.startfile(path) + self.sound_effect(11) + elif os.path.exists(path): + path = path.replace("/", "\\") + subprocess.run(['explorer', '/select,', path]) + self.sound_effect(11) + else: + self.sound_effect(12) + + def sound_effect(self, sound_num): + sound_path = self.sound_effect_list[sound_num] + if os.path.exists(sound_path): + sound = pygame.mixer.Sound(sound_path.replace("\\", "/")) # サウンドファイルを読み込む + sound.play() # サウンドを非同期に再生 + + def on_close(self): + self.cut_modification = True + self.save_cutdata_to_story_txt() + self.window_geometry = self.geometry() + self.save_setting() + self.sound_effect(1) + try: + self.destroy() + except Exception as e: + messagebox.showinfo("エラー", str(e)) + os._exit(0) # プロセスを強制終了 + +# ------ Button Input ------- + + def select_story(self, reload=True): + self.save_cutdata_to_story_txt() + if reload: + self.load_story_and_cut_data() + if not self.story_list: + self.refresh_display_all() + self.add_story() + return + self.sound_effect(9) + selected_index = tk.IntVar(value=-1) + def on_select(event): + selected_index.set(story_listbox.curselection()[0]) + select_window.destroy() + self.sound_effect(2) + parent_x = self.winfo_x() + parent_y = self.winfo_y() + select_window = tk.Toplevel(self, bg="light blue") + select_window.geometry(f"400x730+{parent_x+300}+{parent_y}") + select_window.title("Select Story") + select_window.resizable(False, False) + select_window.attributes('-topmost', True) + select_window.grab_set() + tk.Label(select_window, text="ストーリーを選んで下さい", font=("メイリオ", 20, "bold"), bg="light blue").pack(pady=10) + story_frame = tk.Frame(select_window) + story_frame.pack(padx=10, pady=10) + scrollbar = tk.Scrollbar(story_frame) + scrollbar.pack(side="right", fill="y") + story_listbox = tk.Listbox(story_frame, yscrollcommand=scrollbar.set, width=60, height=40) + story_listbox.pack(side="left", fill="both") + scrollbar.config(command=story_listbox.yview) + for story in self.story_list: + display_name = os.path.splitext(os.path.basename(story))[0] + story_listbox.insert("end", display_name) + story_listbox.bind("<>", on_select) + select_window.wait_window() + index = selected_index.get() + if index == -1: + if reload: + index = 0 + else: + return + self.current_story_index = index + self.refresh_display_all() + + def add_story(self): + self.sound_effect(3) + user_input = simpledialog.askstring("ストーリー追加", f"新規作成するストーリーの名前を入力してください。\n(全角スペースを入れると表示時にそこで改行されます)\n以下の文字は使用不可です。   {self.forbidden_chars_display}", parent=self) + if not user_input: # キャンセルや空入力の場合は処理を中断 + return + forbidden_chars = r'[<>:"/\\|?*]' + if re.search(forbidden_chars, user_input): + error_message = f"使用できない文字が含まれています:{self.forbidden_chars_display}\n{user_input}" + print(error_message) + messagebox.showerror("エラー", error_message) + return + new_story_path = os.path.join(self.stories_path, f"{user_input}.txt").replace('\\', '/') + if not os.path.exists(new_story_path): + with open(new_story_path, 'w', encoding='utf-8') as f: + f.write("||") + else: + messagebox.showinfo("確認", f"既に存在するストーリー名です。\n{self.story_txt_path}",parent=self) + return + self.save_cutdata_to_story_txt() + self.load_story_and_cut_data() + try: + self.current_story_index = self.story_list.index(new_story_path) + except ValueError: + print("no match") + return + self.refresh_display_all() + + def delete_story_txt(self): + if os.path.exists(self.story_txt_path): + self.sound_effect(4) + del_txt_result = messagebox.askyesno("確認", f"選択中ストーリー: {self.story_name}\nのtxtファイルを削除します。\nよろしいですか?", parent=self) + if del_txt_result: + try: + send2trash(os.path.normpath(self.story_txt_path)) # ごみ箱に送る + messagebox.showinfo("確認", f"txtファイルを削除しました。\n{self.story_txt_path}",parent=self) + self.load_story_and_cut_data() + self.refresh_display_all() + self.sound_effect(0) + self.select_story() + except Exception: + messagebox.showinfo("確認", "txtファイルの削除に失敗しました。",parent=self) + else: + messagebox.showinfo("確認", "削除を取り消しました。",parent=self) + else: + messagebox.showinfo("確認", "txtファイルがありません。",parent=self) + + def select_path(self, factor_num): + if not self.story_txt_path: + self.add_story() + return + self.sound_effect(5) + file_path = "" + if factor_num == 0: + file_path = filedialog.askopenfilename( + title=f"CUT# {self.cut_index + 1} の画像ファイルを選んでください。", + filetypes=[("画像ファイル", "*.jpg;*.jpeg;*.gif;*.bmp;*.png;*.webp"),], + parent=self + ) + elif factor_num == 1: + file_path = filedialog.askdirectory( + title=f"CUT# {self.cut_index + 1} の声フォルダを選んでください。", + parent=self + ) + else: + file_path = filedialog.askopenfilename( + title=f"CUT# {self.cut_index + 1} の曲ファイルを選んでください。", + filetypes=[("音声ファイル", "*.mp3;*.wav"),], + parent=self + ) + if not (file_path and os.path.exists(file_path)): + return + self.sound_effect(5) + self.cut_list[self.current_story_index][self.cut_index][factor_num] = file_path.replace('\\', '/') + self.refresh_cut_path() + if factor_num == 0: + self.display_cut_image() + self.cut_modification = True + + def no_bgm(self): + self.sound_effect(5) + self.cut_list[self.current_story_index][self.cut_index][2] = "NO" + self.refresh_cut_path() + self.cut_modification = True + + def delete_path(self, factor_num): + if not self.cut_list[self.current_story_index][self.cut_index][factor_num]: + self.sound_effect(12) + return + self.sound_effect(6) + factor = ["画像ファイル", "声フォルダ", "曲ファイル"] + delete_result = messagebox.askyesno("確認", f"CUT# {self.cut_index + 1} の{factor[factor_num]}を削除します。\nよろしいですか?", parent=self) + if delete_result: + self.cut_list[self.current_story_index][self.cut_index][factor_num] = "" + print("delete:", self.cut_list[self.current_story_index][self.cut_index]) + else: + messagebox.showinfo("確認", "削除を取り消しました。",parent=self) + return + self.refresh_cut_path() + if factor_num == 0: + self.image_canvas.delete("all") + self.cut_modification = True + messagebox.showinfo("確認", f"CUT# {self.cut_index + 1} の{factor[factor_num]}を削除しました。",parent=self) + + def edit_text(self): + voice_folder_path = self.cut_list[self.current_story_index][self.cut_index][1] + if not os.path.exists(voice_folder_path): + self.sound_effect(12) + return + txt_file_path = os.path.join(voice_folder_path, "SCENARIO.txt").replace('\\', '/') + if not os.path.exists(txt_file_path): + try: + with open(txt_file_path, "w", encoding="utf-8") as f: + f.write("") # 空のファイルを作成 + except Exception as e: + messagebox.showinfo("エラー", f"ファイルの作成に失敗しました: {e}", parent=self) + return + try: + subprocess.run( + f'start "" "{txt_file_path}"', + shell=True, + check=True + ) + self.sound_effect(5) + except Exception as e: + messagebox.showinfo("エラー", str(e), parent=self) + + def add_cut(self): + if not self.story_list: + self.add_story() + return + self.sound_effect(3) + self.cut_index += 1 + self.cut_list[self.current_story_index].insert(self.cut_index, ["", "", ""]) + self.display_cut_data() + self.cut_modification = True + + def delete_cut(self): + if not self.story_list or self.total_cut_num <= 1: + return + self.sound_effect(4) + delete_result = messagebox.askyesno("確認", f"CUT# {self.cut_index + 1} を削除します。\nよろしいですか?", parent=self) + if delete_result: + delete_index = self.cut_index + self.cut_list[self.current_story_index].pop(delete_index) + self.total_cut_num = len(self.cut_list[self.current_story_index]) + self.cut_index -= 1 + self.cut_index = max(self.cut_index, 0) + self.total_cut_num = max(self.total_cut_num, 0) + self.display_cut_data() + self.cut_modification = True + self.save_cutdata_to_story_txt() + self.sound_effect(4) + messagebox.showinfo("確認", f"CUT# {delete_index + 1} を削除しました。",parent=self) + else: + messagebox.showinfo("確認", "削除を取り消しました。",parent=self) + + def move_cut(self): + if not self.story_list: + self.add_story() + return + self.sound_effect(7) + self.move_cut_index = self.cut_index + geometry = self.geometry() + plot = geometry.split("+") + x, y = plot[1], plot[2] + self.move_cut_window = tk.Toplevel(self, bg="aquamarine") + self.move_cut_window.geometry(f"500x730+{x}+{y}") + self.move_cut_window.resizable(False, False) + self.move_cut_window.transient(self) + self.move_cut_window.grab_set() + self.move_cut_window.title(f"CUT #{self.cut_index + 1}の移動先を選択") + + self.text_id = self.image_canvas.create_text(240, 240, text="←", font=("メイリオ", 100, "bold"), fill="yellow", anchor="center") + + move_title_frame = tk.Frame(self.move_cut_window, bg="dark green") + move_title_frame.grid(row= 0, column= 0, columnspan=4, padx= 10, pady= 5, sticky="new") + cut_move_to_label = tk.Label(move_title_frame, text="MOVE TO", bg="dark green", fg="white", font=("Arial Black", 25, "bold"), justify="left", anchor="w") + cut_move_to_label.grid(row=0, column=0, sticky="w") + move_title_frame.grid_columnconfigure(1, weight=1) + self.cut_move_index_label = tk.Label(move_title_frame, bg="dark green", fg="white", font=("Arial Black", 25, "bold"), justify="right", anchor="e") + self.cut_move_index_label.grid(row=0, column=2, columnspan=2, sticky="e") + # 画像表示 + self.move_image_canvas = tk.Canvas(self.move_cut_window, bg="black", highlightthickness=0, bd=0, width= 450, height= 450) + self.move_image_canvas.grid(row=1, column=0, columnspan=4, padx=25, pady=25, sticky="news") + + move_window_button_frame = tk.Frame(self.move_cut_window, bg="dark green") + move_window_button_frame.grid(row= 2, column= 0, columnspan=4, padx= 10, pady= 5, sticky="ew") + head_cut_button = tk.Button(move_window_button_frame, text="|◀", font=("Arial", 15), command=lambda:self.seek_move_cut_button(-1000), bg="blue", fg="white") + head_cut_button.grid(row= 0, column= 0, padx= 5, pady= 15, sticky="w") + minus_5_button = tk.Button(move_window_button_frame, text="◀ 5", font=("Arial", 15), command=lambda:self.seek_move_cut_button(-5), bg="blue", fg="white") + minus_5_button.grid(row= 0, column= 1, padx= 5, pady= 15, sticky="w") + previous_button = tk.Button(move_window_button_frame, text=" ◀ ", font=("Arial", 15), command=lambda:self.seek_move_cut_button(-1), bg="blue", fg="white") + previous_button.grid(row= 0, column= 2, padx= 5, pady= 15) + move_window_button_frame.grid_columnconfigure(3, weight=1) + next_button = tk.Button(move_window_button_frame, text=" ▶ ", font=("Arial", 15), command=lambda:self.seek_move_cut_button(1), bg="blue", fg="white") + next_button.grid(row= 0, column= 4, padx= 5, pady= 15) + plus_5_button = tk.Button(move_window_button_frame, text="5 ▶", font=("Arial", 15), command=lambda:self.seek_move_cut_button(5), bg="blue", fg="white") + plus_5_button.grid(row= 0, column= 5, padx= 5, pady= 15, sticky="e") + last_cut_button = tk.Button(move_window_button_frame, text="▶|", font=("Arial", 15), command=lambda:self.seek_move_cut_button(1000), bg="blue", fg="white") + last_cut_button.grid(row= 0, column= 6, padx= 5, pady= 15, sticky="e") + # 操作ボタンフレーム + move_to_head_button = tk.Button(self.move_cut_window, text="先頭に移動", font=("Arial", 15, "bold"), command=lambda:self.execution_move(0), bg="gold") + move_to_head_button.grid(row= 3, column= 0, padx= 5, pady= 30, sticky="sw") + move_to_select_index_button = tk.Button(self.move_cut_window, text="選択画像の次に移動", font=("Arial", 15, "bold"), command=lambda:self.execution_move(self.move_cut_index), bg="gold") + move_to_select_index_button.grid(row= 3, column= 1, padx= 5, pady= 30) + move_to_last_button = tk.Button(self.move_cut_window, text="最後に移動", font=("Arial", 15, "bold"), command=lambda:self.execution_move(self.total_cut_num - 1), bg="gold") + move_to_last_button.grid(row= 3, column= 2, padx= 5, pady= 30, sticky="se") + self.move_cut_window.bind("", lambda event: self.select_move_cut_wheel(event)) + self.move_cut_window.protocol("WM_DELETE_WINDOW", lambda event=None:self.move_window_on_close()) + self.seek_move_cut_button(0) + + def seek_move_cut_button(self, seek_num): + self.sound_effect(8) + self.move_cut_index += seek_num + self.move_cut_index = max(min(self.move_cut_index, self.total_cut_num - 1), 0) + self.cut_move_index_label.config(text=f"{self.move_cut_index + 1} / {self.total_cut_num}") + self.move_image_canvas.delete("all") + path = self.cut_list[self.current_story_index][self.move_cut_index][0] + if not (path and os.path.exists(path)): + return + image = Image.open(path) + image.thumbnail((450, 450), Image.LANCZOS) + resize_width, resize_height = image.size + x_center = (450 - resize_width) // 2 + y_center = (450 - resize_height) // 2 + tk_image = ImageTk.PhotoImage(image) + self.move_image_canvas.create_image(x_center, y_center, anchor="nw", image=tk_image) + self.move_image_canvas.image = tk_image + + def execution_move(self, move_to_index): + if move_to_index == self.cut_index: + self.sound_effect(12) + return + self.sound_effect(7) + move_cut = self.cut_list[self.current_story_index].pop(self.cut_index) + self.cut_list[self.current_story_index].insert(move_to_index, move_cut) + self.cut_index = self.move_cut_index + self.move_window_on_close() + + def move_window_on_close(self): + self.image_canvas.delete(self.text_id) + self.move_cut_window.destroy() + self.display_cut_data() + + def cut_divide(self): + voice_folder_path = self.cut_list[self.current_story_index][self.cut_index][1] + if not self.story_list or not os.path.exists(voice_folder_path): + self.sound_effect(12) + return + divide_num = simpledialog.askinteger("カットの分割", f"CUT# {self.cut_index + 1}\nVOICEフォルダ:\n{voice_folder_path}\n\n入力された再生番号以降の\n声ファイルとSCENARIO.txtの内容を\n新規作成したVOICEフォルダに移します。", parent=self) + if not divide_num: + return + audio_files = [ + os.path.basename(f).replace("\\", "/") # ファイル名のみをリストに + for f in os.listdir(voice_folder_path) + if f.lower().endswith((".mp3", ".wav")) + ] + move_file_list = [] + for file in audio_files: + first_part = file.split("_")[0] + if first_part.isdigit(): + order_num = int(first_part) + if order_num >= divide_num: + move_file_list.append(file) + if not move_file_list: + messagebox.showinfo("確認", "移動する声ファイルがありません。",parent=self) + return + execution = messagebox.askyesno("確認", f"{len(audio_files)}個中 {len(move_file_list)}個の声ファイルを新しいフォルダに移動します。\nよろしいですか?", parent=self) + if not execution: + return + parent_folder = os.path.dirname(voice_folder_path) + basename = re.sub(r"_\d+$", "", os.path.basename(voice_folder_path)) + counter = 1 + while True: + new_folder_path = os.path.join(parent_folder, f"{basename}_{counter}").replace("\\", "/") + if not os.path.exists(new_folder_path): + break + counter += 1 + os.mkdir(new_folder_path) + try: + for file in move_file_list: + move_file_path = os.path.join(voice_folder_path, file).replace("\\", "/") + shutil.move(move_file_path, new_folder_path) + except Exception as e: + print(str(e)) + messagebox.showinfo("エラー", str(e)) + self.divide_txt(voice_folder_path, new_folder_path, divide_num) + self.cut_index += 1 + self.cut_list[self.current_story_index].insert(self.cut_index, ["", new_folder_path, ""]) + self.sound_effect(3) + self.display_cut_data() + + def divide_txt(self, voice_folder_path, new_folder_path, divide_num): + txt_path = os.path.join(voice_folder_path, "SCENARIO.txt").replace("\\", "/") + text = self.read_txt(txt_path) + if text: + old_file_text = "" + new_file_text = "" + split_text = text.splitlines() + for line in split_text: + first_part = line.split("_")[0] + if first_part.isdigit(): + order_num = int(first_part) + if order_num >= divide_num: + new_file_text += line + "\n" + else: + old_file_text += line + "\n" + new_txt_path = os.path.join(new_folder_path, "SCENARIO.txt").replace("\\", "/") + try: + with open(txt_path, "w", encoding="utf-8") as file1: + file1.write(old_file_text.strip()) + with open(new_txt_path, "w", encoding="utf-8") as file2: + file2.write(new_file_text.strip()) + except Exception as e: + messagebox.showinfo("エラー", f"ファイルの作成に失敗しました: {e}", parent=self) + + def read_txt(self, txt_path): + if os.path.exists(txt_path): + encoding = self.detect_encoding(txt_path) + if encoding: + try: + with open(txt_path, "r", encoding=encoding) as file: + return file.read().strip() + except Exception as e: + print(str(e)) + messagebox.showinfo("エラー", str(e)) + return None + return None + + def seek_cut_button(self, seek_num): + if not self.story_list: + self.add_story() + return + self.sound_effect(8) + self.cut_index += seek_num + self.cut_index = max(min(self.cut_index, self.total_cut_num - 1), 0) + self.display_cut_data() + +# ------ Mouse Wheel ------- + + def select_story_wheel(self, event): + if not self.story_list: + self.add_story() + return + self.sound_effect(2) + if event.delta > 0: + self.current_story_index -= 1 + else: + self.current_story_index += 1 + self.current_story_index = max(min(self.current_story_index, self.total_story_num - 1), 0) + self.cut_index = 0 + self.refresh_display_all() + + def select_cut_wheel(self, event): + if event.delta > 0: + self.seek_cut_button(-1) + else: + self.seek_cut_button(1) + + def select_move_cut_wheel(self, event): + if event.delta > 0: + self.seek_move_cut_button(-1) + else: + self.seek_move_cut_button(1) + + def character_settings_wheel(self, event): + if event.delta > 0: + self.seek_char_button(-1) + else: + self.seek_char_button(1) + + def change_volume(self, event): + """マウスホイールで音量を変更""" + if event.delta > 0: + self.volume = min(self.volume + 5, 100) + else: + self.volume = max(self.volume - 5, 0) + pygame.mixer.music.set_volume(self.volume / 100) + self.update_volume(self.volume) + + def update_volume(self, volume): + """音量を更新し、タイトルを変更""" + if hasattr(self, 'reset_timer') and self.reset_timer: + self.after_cancel(self.reset_timer) + self.play_window.title(f"Volume: 🔈{volume}%") + self.reset_timer = self.after(2000, lambda: self.display_title()) + +# ------ Play Story ------- + + def display_play_window(self, event=None): + self.save_cutdata_to_story_txt() + self.iconify() + self.play_window = tk.Toplevel(self) + self.play_window.bind("", self.change_volume) + self.play_window.bind("", lambda event=None: self.next_voice()) + self.play_window.bind("", lambda event=None: self.play_window_close()) + self.play_window.bind("", lambda event: self.seek_play_index(1, event)) + self.play_window.bind("", lambda event: self.seek_play_index(-1, event)) + self.play_window.bind("", lambda event=None: self.play_window.iconify()) + self.play_window.protocol("WM_DELETE_WINDOW", lambda event=None: self.play_window_close()) + self.play_window.bind("",lambda event=None: self.play_window_close()) + self.play_window.bind("", lambda event: self.play_window_resize_event(event)) + + if self.full_screen: + self.play_window.attributes('-fullscreen', True) + self.play_window.overrideredirect(True) + self.play_window.attributes('-topmost', True) + else: + self.play_window.geometry(self.play_window_geometry) + self.play_window.focus_force() + self.play_window.grab_set() + self.play_canvas = tk.Canvas(self.play_window, bg="black" ,bd=0, highlightthickness=0) + self.play_canvas.pack(fill="both", expand=True) + self.interval = self.voice_interval / 1000 + if self.play_mode[self.current_story_index] == 2: + if not os.path.isdir(self.random_image_folder[self.current_story_index]): + return + else: + folder_path = self.random_image_folder[self.current_story_index] # フルパスを取得 + files = os.listdir(folder_path) # フォルダ内のファイルリスト取得 + self.random_image_files = [ + os.path.join(folder_path, file) for file in files + if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.mp4', '.webm')) + ] + if self.random_image_files: + self.total = len(self.random_image_files) + self.play_index = 0 + self.index = 0 + else: + return + else: + self.play_index = self.cut_index + self.index = self.play_index + self.total = len(self.cut_list[self.current_story_index]) + if self.random[self.current_story_index]: + self.order_table = list(range(self.total)) + random.shuffle(self.order_table) + self.img = "" + self.music_title = "" + self.text_foreground_id = None + self.text_background_id_list = [None] * 16 + self.empty_image = ImageTk.PhotoImage(Image.new("RGBA", (1, 1), (255, 255, 255, 0))) + self.image_id = self.play_canvas.create_image(0, 0, anchor=tk.NW, image=self.empty_image) + for i in range(16): + self.text_background_id_list[i] = self.play_canvas.create_text(0, -100, text="", fill="black") + self.play_canvas.tag_raise(self.text_background_id_list[i]) + self.text_foreground_id = self.play_canvas.create_text(0, -100, text="", fill="black") + self.play_canvas.tag_raise(self.text_foreground_id) + if self.play_index == 0: + self.character_dict = {c["name"]: (c["font"], c["size"], c["style"], c["color"], c["color2"], c["edge"], c["position"]) for c in self.character_list} + self.play_window.update() + self.play_canvas.update_idletasks() + self.current_size = (self.play_window.winfo_width(), self.play_window.winfo_height()) + self.play_story() + + def delete_text(self): + if hasattr(self, 'play_canvas') and self.play_canvas: + for text_id in self.text_background_id_list: + self.play_canvas.delete(text_id) + self.play_canvas.delete(self.text_foreground_id) + + def reset_image_id(self): + if hasattr(self, 'play_canvas') and self.play_canvas: + self.play_canvas.coords(self.image_id, 0, 0) + self.play_canvas.itemconfig(self.image_id, image=self.empty_image) + + def play_window_resize_event(self, event): + if hasattr(self, 'resize_timer') and self.resize_timer: + self.after_cancel(self.resize_timer) + self.resize_timer = self.after(200, self.check_if_resized) + + def check_if_resized(self): + if self.play_window and self.play_window.winfo_exists(): + new_size = (self.play_window.winfo_width(), self.play_window.winfo_height()) + if new_size != self.current_size: # サイズが変わっている場合 + self.current_size = new_size + self.on_resize() # サイズが確定したときに一度だけ呼び出す + + def on_resize(self): + self.reset_image_id() + if os.path.exists(self.img): + self.display_image(self.img) + if self.display_text: + self.display_lines() + + def display_title(self): + if self.play_window.winfo_exists(): # ウィンドウが存在する場合のみ + if self.music_title: + music_name = f"♪{self.music_title}♪" + else: + music_name = "" + self.play_window.title(f"【{self.story_name}】 CUT# {self.index + 1} / {self.total} {music_name}") + + def play_bgm(self, bgm): + self.bgm = bgm + if pygame.mixer.music.get_busy(): + pygame.mixer.music.stop() + self.music_title = "" + if os.path.exists(bgm): + pygame.mixer.music.load(bgm) + pygame.mixer.music.play(-1) + self.music_title = f"{os.path.splitext(os.path.basename(bgm))[0]}" + + def play_story(self): + if self.playing: + return + if self.random[self.current_story_index]: + self.index = self.order_table[self.play_index] + else: + self.index = self.play_index + self.interruption = True + self.playing = True + self.start_time = time.time() + if hasattr(self, 'voice_thread') and self.voice_thread.is_alive(): + print("Stopping previous voice thread...") + self.interruption = True + self.voice_thread.join() + self.interruption = False + if self.play_mode[self.current_story_index] == 2: + bgm = self.cut_list[self.current_story_index][0][2] + else: + bgm = self.cut_list[self.current_story_index][self.index][2] + if bgm == "NO": + if pygame.mixer.music.get_busy(): + pygame.mixer.music.stop() + self.music_title = "" + elif bgm and os.path.exists(bgm): + if bgm == self.bgm and pygame.mixer.music.get_busy(): + pass + else: + self.play_bgm(bgm) + elif pygame.mixer.music.get_busy(): + pass + elif self.default_bgm: + bgm = self.cut_list[self.current_story_index][0][2] + if bgm and os.path.exists(bgm): + self.play_bgm(bgm) + self.display_title() + if self.play_mode[self.current_story_index] == 2: + self.img = self.random_image_files[self.index] + else: + self.img = self.cut_list[self.current_story_index][self.index][0] + if self.img: + if os.path.exists(self.img): + self.display_image(self.img) + else: + img_filename = os.path.basename(self.img) + voice_folder_path = os.path.dirname(self.cut_list[self.current_story_index][0][1]) + self.img = os.path.join(voice_folder_path, img_filename).replace('\\', '/') + if os.path.exists(self.img): + self.display_image(self.img) + if self.play_mode[self.current_story_index] == 2: + voice_folder_path = self.cut_list[self.current_story_index][0][1] + else: + voice_folder_path = self.cut_list[self.current_story_index][self.index][1] + if not os.path.exists(voice_folder_path): + voice_folder_name = os.path.basename(voice_folder_path) + cut_1_voice__path = os.path.dirname(self.cut_list[self.current_story_index][0][1]) + voice_folder_path = os.path.join(cut_1_voice__path, voice_folder_name).replace('\\', '/') + self.voice_thread = threading.Thread( + target=self.play_folder_voice, + args=(voice_folder_path,) + ) + self.voice_thread.start() + self.after(100, self.Continuous_playback) + + def Continuous_playback(self): + if self.interruption: # 停止フラグが立っている場合は実行しない + self.playing = False + return + yet_min_display = (time.time() - self.start_time) < self.min_display[self.current_story_index] + if (hasattr(self, 'voice_thread') and self.voice_thread.is_alive()) or yet_min_display: + self.after(100, self.Continuous_playback) # 音声再生が終わるまで待機 + else: + self.playing = False # 再生フラグをリセット + self.play_index += 1 + self.play_index = self.play_index % self.total + self.play_story() + + def stop_playing(self, event=None): + self.interruption = True # 再生停止フラグを立てる + self.playing = False + # 再生スレッドの強制終了 + if hasattr(self, 'voice_thread') and self.voice_thread.is_alive(): + self.voice_thread.join(timeout=1) + + def play_voice(self, voice_file_path, text_length, play_time): + # サウンドを順番に再生する + self.skip_voice = False + if voice_file_path and os.path.exists(voice_file_path): + # 音声をロード + self.voice = pygame.mixer.Sound(voice_file_path.replace("\\", "/")) # サウンドを読み込む + if play_time: + wait_time = play_time + else: + wait_time = self.voice.get_length() # 音声の長さを取得 + # 音声を再生 + self.voice.play() + else: + wait_time = text_length * self.sec_per_char / 1000 + time_counter = 0 + # 再生中に中断フラグを監視 + while time_counter < wait_time: + if self.interruption: + if hasattr(self, 'voice') and self.voice: + self.voice.stop() + self.voice = None + return + if self.skip_voice: + if hasattr(self, 'voice') and self.voice: + self.voice.stop() + self.voice = None + break + time.sleep(0.03) + time_counter += 0.03 + # 再生終了後にリセット + self.voice = None + + def next_voice(self): + self.sound_effect(13) + self.skip_voice = True + + def detect_encoding(self, file_path): + with open(file_path, "rb") as f: + raw_data = f.read() + result = chardet.detect(raw_data) + return result["encoding"] + + def read_scenario_txt(self, path): + lines_dict = {} + if path: + txt_path = os.path.join(path, "SCENARIO.txt").replace('\\', '/') + text = self.read_txt(txt_path) + else: + text = None + if text: + split_text = text.splitlines() + for line in split_text: + line_data = line.split("_") + if line_data[0].isdigit(): + num = int(line_data[0]) + if len(line_data) > 3: + play_time = line_data[3] + else: + play_time = None + lines_dict[num] = (None, line_data[1], line_data[2], play_time) + return lines_dict + + def play_folder_voice(self, path): + audio_files = [] + if self.play_mode[self.current_story_index] == 0: + lines_dict = self.read_scenario_txt(path) + if os.path.exists(path): + files = os.listdir(path) + audio_files = [ + file for file in files + if file.lower().endswith((".mp3", ".wav")) and re.match(r"^\d+_", file) + ] + if audio_files: + for file in audio_files: + match = file.split("_")[0] + if match.isdigit(): + num = int(match) + if num in lines_dict: + lines_dict[num] = (file, lines_dict[num][1], lines_dict[num][2], lines_dict[num][3]) + else: + lines_dict[num] = (file, None, None, None) + # 辞書を数値でソートしてリストを作成 + merged_list = sorted(lines_dict.items(), key=lambda x: x[0]) + indexed_list = [(data[0], data[1], data[2], data[3]) for _, data in merged_list] + else: + indexed_list = [] + if os.path.exists(path): + files = os.listdir(path) + audio_files = [ + file for file in files + if file.lower().endswith((".mp3", ".wav"))] + if audio_files: + m = len(audio_files) + n = self.random_voice_num[self.current_story_index] + if m < n: + n = m + random_numbers = random.sample(range(m), n) + for i in range(n): + indexed_list.append([audio_files[random_numbers[i]], None, None, None] ) + + for lines_data in indexed_list: + if not self.play_canvas.winfo_exists(): + return + self.display_text = lines_data[2] + self.delete_text() + if self.display_text: + self.display_text = self.text_line_breaks(self.display_text.replace(' ', '\n')) + text_length = len(self.display_text) + self.display_lines(lines_data[1]) + else: + text_length = 0 + if lines_data[0]: + voice_file_path = os.path.join(path, lines_data[0]).replace("\\", "/") + else: + voice_file_path = None + try: + play_time = float(lines_data[3]) + except (ValueError, TypeError): # TypeError もキャッチ + play_time = None + self.play_voice(voice_file_path, text_length, play_time) + if play_time: + continue + time_counter = 0 + while time_counter < self.interval: + if self.interruption: + return + time.sleep(0.03) + time_counter += 0.03 + + def display_lines(self, talking_character): + for i, character in enumerate(self.character_list): + if i == 0 or character["name"] in talking_character: + font = character["font"] + size = character["size"] + style = character["style"] + color = character["color"] + color2 = character["color2"] + edge = character["edge"] + position = character["position"] + if i != 0: + break + width, height = self.current_size + line_position_x = width // 2 + line_position_y = height // 100 * (107 - position) + if self.adjust_font_size: + size = int(size * height / self.screen_height) + if edge: + self.text_background_id_list = [ + self.play_canvas.create_text( + line_position_x + x, line_position_y + y, + text=self.display_text, fill=color2, + font=(font, size, style) + ) + for x, y in self.edge_plot[edge - 1] + ] + # 前景テキストを新規作成 + self.text_foreground_id = self.play_canvas.create_text( + line_position_x, line_position_y, + text=self.display_text, fill=color, + font=(font, size, style)) + + def text_line_breaks(self, text): + result = "" + current_line = "" + last_punctuation_pos = -1 + for char in text: + current_line += char + if char == '\n': + result += current_line + current_line = "" + last_punctuation_pos = -1 + continue + if char in self.punctuation_marks: + last_punctuation_pos = len(current_line) + if len(current_line) >= self.line_break: + if last_punctuation_pos != -1: + result += current_line[:last_punctuation_pos] + "\n" + current_line = current_line[last_punctuation_pos:] + last_punctuation_pos = -1 + else: + result += current_line + "\n" + current_line = "" + result += current_line + return result + + def reset_media_display(self): + self.update_idletasks() # 更新を反映 + self.video_playing = False + # 既存のアニメーション再生を停止(コールバックをキャンセル) + if hasattr(self, 'animation_after_id') and self.animation_after_id is not None: + try: + self.play_canvas.after_cancel(self.animation_after_id) + self.animation_after_id = None + except Exception as e: + print(f"Error canceling animation: {e}") + self.current_frame = 0 # フレームインデックスをリセット + # その他の状態をリセット + self.delete_text() + self.reset_image_id() + + def display_image(self, path): + self.reset_media_display() + self.play_window.update() + self.play_canvas.update_idletasks() + if self.full_screen: + window_width, window_height = self.screen_width, self.screen_height + else: + window_width, window_height = self.current_size = (self.play_window.winfo_width(), self.play_window.winfo_height()) + _, extension = os.path.splitext(self.img) + if extension in ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp'): + image = Image.open(path) + self.set_frame_size(image.width, image.height, window_width, window_height) + if extension in ('.gif', '.webp'): + if not getattr(self.img, "is_animated", False): + self.show_gif_webp_anime(image) + return + self.update_idletasks() + image = image.resize((self.new_width, self.new_height )) + photo = ImageTk.PhotoImage(image) + self.play_canvas.itemconfig(self.image_id, image=photo) + self.play_canvas.image = photo + self.play_canvas.tag_lower(self.image_id) # 背景に移動 + elif extension in ('.mp4', '.webm'): + video_width, video_height, self.fps, self.total_frames = self.get_video_info(path) + self.set_frame_size(video_width, video_height, window_width, window_height) + self.frame_delay = int(1000 / self.fps) # 1フレームの表示時間(ms) + self.frame_size = self.new_width * self.new_height * 3 # RGB なので 3 倍 + self.process = None + self.timeout_count = 0 + self.start_video(path) + + def set_frame_size(self, img_width, img_height, window_width, window_height): + self.new_width, self.new_height = self.size_frame_in(img_width, img_height, window_width, window_height) + x_center = (window_width - self.new_width) // 2 + y_center = (window_height - self.new_height) // 2 + self.play_canvas.coords(self.image_id, x_center, y_center) + + def start_video(self, path): + self.get_process(path) + self.video_playing = True + self.show_video_frame(path) + + def size_frame_in(self, img_width, img_height, frm_width, frm_height): + img_aspect_ratio = img_width / max(img_height,1) + frame_aspect_ratio = frm_width / max(frm_height,1) + if img_aspect_ratio > frame_aspect_ratio: + new_width = frm_width + new_height = int(frm_width / img_aspect_ratio) + else: + new_height = frm_height + new_width = int(frm_height * img_aspect_ratio) + new_width = max(new_width, 1) + new_height = max(new_height, 1) + return new_width, new_height + + def seek_play_index(self, value, event=None): + self.stop_playing() + self.play_index += value + self.play_index = self.play_index % self.total + self.sound_effect(8) + self.play_story() + + def play_window_close(self, event=None): + self.stop_playing() + pygame.mixer.music.stop() + self.play_window_geometry = self.play_window.geometry() + self.sound_effect(10) + if self.play_window.winfo_exists(): + self.play_window.destroy() + self.deiconify() + self.after(100, lambda: self.attributes('-topmost', True)) + self.after(200, lambda: self.attributes('-topmost', False)) + +#-----------animation gif, webp------------------- + + def show_gif_webp_anime(self, image): + self.animation_frames = [] + # デフォルト遅延時間を設定 + first_frame = next(ImageSequence.Iterator(image)) # 最初のフレームを取得 + animation_delay = first_frame.info.get('duration', 100) or 100 + animation_delay = max(50, min(animation_delay, 500)) # 50ms 〜 500ms に制限 + # 各���レームを取得し、リサイズ後にリストに格納 + for frame in ImageSequence.Iterator(image): + frame_image_resized = frame.copy().resize((self.new_width, self.new_height), Image.LANCZOS) + self.animation_frames.append(ImageTk.PhotoImage(frame_image_resized)) + self.total_frames = len(self.animation_frames) + print("animation_delay, total_frames\n", animation_delay, self.total_frames, self.new_width, self.new_height) + self.current_frame_index = 0 # 最初のフレームから開始 + self.video_playing = True + self.play_animation(animation_delay) # 遅延時間も引き渡す + + def play_animation(self, animation_delay): + if not (self.animation_frames and self.video_playing): + print("came") + return + # 事前に作成した `PhotoImage` を使用 + photo = self.animation_frames[self.current_frame_index] + self.play_canvas.image = photo # 参照を保持 + self.play_canvas.itemconfig(self.image_id, image=photo) + self.current_frame_index = (self.current_frame_index + 1) % self.total_frames + print(self.current_frame_index) + # `play_canvas` の `after()` を使用 + self.animation_after_id = self.play_canvas.after(animation_delay, lambda: self.play_animation(animation_delay)) + +#-----------animation mp4, webm------------------- + + def get_video_info(self, video_path): + ffprobe_cmd = [ + "ffprobe", "-v", "error", + "-select_streams", "v:0", + "-show_entries", "stream=width,height,r_frame_rate,nb_frames", + "-of", "json", + video_path + ] + result = subprocess.run(ffprobe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, creationflags=subprocess.CREATE_NO_WINDOW) + if result.returncode != 0: + print("FFprobe error:", result.stderr) + return None + info = json.loads(result.stdout).get("streams", []) + if info: + stream = info[0] + width = stream.get("width", 0) + height = stream.get("height", 0) + fps = eval(stream.get("r_frame_rate", "0/1")) # "30000/1001" → 29.97 + total_frames = int(stream.get("nb_frames", 0)) + print("width, height, fps, total_frames\n", width, height, fps, total_frames) + return width, height, fps, total_frames + return None + + def get_process(self, path): + command = [ + 'ffmpeg', '-stream_loop', '-1', # 無限ループ再生 + '-i', path, + '-threads', '4', + '-vf', f'scale={self.new_width}:{self.new_height}', + '-c:v', 'rawvideo', + '-f', 'rawvideo', + '-pix_fmt', 'rgb24', + '-' + ] + self.process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW) + + def show_video_frame(self, media_path): + if not (self.process and self.video_playing): + return + in_bytes = self.read_with_timeout(self.frame_size) + # 動画の終端に達した場合、待機して次のフレームを読む + if in_bytes is None or len(in_bytes) != self.frame_size: + print("動画の終端に達したが、リピート再生を継続") + self.play_canvas.after(self.frame_delay, self.show_video_frame, media_path) + return + try: + frame = np.frombuffer(in_bytes, np.uint8).reshape([self.new_height, self.new_width, 3]) + except Exception as e: + messagebox.showinfo("エラー", str(e), parent=self) + return + # フレーム描画 + image = Image.fromarray(frame) + photo = ImageTk.PhotoImage(image) + self.play_canvas.image = photo + self.play_canvas.itemconfig(self.image_id, image=photo) + self.play_canvas.tag_lower(self.image_id) + if self.video_playing: + self.animation_after_id = self.play_canvas.after(self.frame_delay, self.show_video_frame, media_path) + + def read_with_timeout(self, frame_size, timeout=1.0): + in_bytes = [None] + def read_from_stdout(): + try: + in_bytes[0] = self.process.stdout.read(frame_size) + except Exception as e: + print("エラー:", e) + thread = threading.Thread(target=read_from_stdout) + thread.start() + thread.join(timeout) + if thread.is_alive(): + self.timeout_count += 1 + print(f"タイムアウト発生: {self.timeout_count}") + return None + else: + self.timeout_count = 0 + return in_bytes[0] + +# ------ Setting Window ------- + + def open_character_settings_window(self): + self.sound_effect(9) + geometry = self.geometry() + plot = geometry.split("+") + x, y = int(plot[1]), int(plot[2]) + self.character_settings_window = tk.Toplevel(self, bg="peach puff") + self.character_settings_window.geometry(f"485x590+{x+262}+{y+70}") + self.character_settings_window.resizable(False, False) + self.character_settings_window.transient(self) + self.character_settings_window.grab_set() + self.character_settings_window.title("キャラクター セリフ表示設定") + self.character_index = 0 + self.total_char_num = len(self.character_list) + self.character_settings_window.bind("",lambda event: self.character_settings_wheel(event)) + + char_title_frame = tk.Frame(self.character_settings_window, bg="orange") + char_title_frame.grid(row= 0, column= 0, columnspan=4, padx= 10, pady= 10, sticky="news") + tk.Label(char_title_frame, text="CHARACTER", bg="orange", font=("Arial Black", 25, "bold"), justify="left").grid(row=0, column=0, sticky="w") + char_title_frame.grid_columnconfigure(1, weight=1) + self.character_index_label = tk.Label(char_title_frame, font=("Arial Black", 25, "bold"), justify="right", bg="orange") + self.character_index_label.grid(row=0, column=2, padx=10, pady=10, sticky="e") + + self.name_canvas = tk.Canvas(self.character_settings_window, bg="peach puff", highlightthickness=0, bd=0, width=465, height=50) + self.name_canvas.grid(row=1, column=0, columnspan=4, padx=10, pady=10, sticky="we") + + operation_button_frame = tk.Frame(self.character_settings_window, bg="orange") + operation_button_frame.grid(row= 2, column= 0, columnspan=4, padx= 10, pady= 5, sticky="we") + head_cut_button = tk.Button(operation_button_frame, text="|◀", font=("Arial", 15), command=lambda:self.seek_char_button(-1000), bg="blue", fg="white") + head_cut_button.grid(row= 0, column= 0, padx= 5, pady= 5, sticky="w") + minus_5_button = tk.Button(operation_button_frame, text="◀ 5", font=("Arial", 15), command=lambda:self.seek_char_button(-5), bg="blue", fg="white") + minus_5_button.grid(row= 0, column= 1, padx= 5, pady= 5, sticky="w") + previous_button = tk.Button(operation_button_frame, text=" ◀ ", font=("Arial", 15), command=lambda:self.seek_char_button(-1), bg="blue", fg="white") + previous_button.grid(row= 0, column= 2, padx= 5, pady= 5, sticky="w") + operation_button_frame.grid_columnconfigure(3, weight=1) + change_character_name_button = tk.Button(operation_button_frame, text="キャラ名変更", font=("メイリオ", 15, "bold"), command=lambda:self.change_character_name(), bg="yellow", fg="red") + change_character_name_button.grid(row= 0, column= 4, padx= 5, pady= 5) + operation_button_frame.grid_columnconfigure(5, weight=1) + next_button = tk.Button(operation_button_frame, text=" ▶ ", font=("Arial", 15), command=lambda:self.seek_char_button(1), bg="blue", fg="white") + next_button.grid(row= 0, column= 6, padx= 5, pady= 5, sticky="e") + plus_5_button = tk.Button(operation_button_frame, text="5 ▶", font=("Arial", 15), command=lambda:self.seek_char_button(5), bg="blue", fg="white") + plus_5_button.grid(row= 0, column= 7, padx= 5, pady= 5, sticky="e") + last_cut_button = tk.Button(operation_button_frame, text="▶|", font=("Arial", 15), command=lambda:self.seek_char_button(1000), bg="blue", fg="white") + last_cut_button.grid(row= 0, column= 8, padx= 5, pady= 5, sticky="e") + # フォント 選択ボタン + tk.Button(self.character_settings_window, text="フォント選択:", command=lambda :self.select_font()).grid(row=3, column=0, padx=10, pady=10, sticky="w") + self.font_canvas = tk.Canvas(self.character_settings_window, bg="peach puff", highlightthickness=0, bd=0, width=230, height=30) + self.font_canvas.grid(row=3, column=1, columnspan=3, padx=10, pady=10, sticky="w") + # フォントサイズ入力 + self.font_size_var = tk.IntVar(value=self.character_list[self.character_index]["size"]) + tk.Label(self.character_settings_window, text="フォントサイズ:", bg="peach puff").grid(row=4, column=0, padx=10, pady=10, sticky="w") + tk.Spinbox(self.character_settings_window, from_=5, to=80, textvariable=self.font_size_var, width=4, command=lambda :self.rewrite_dict()).grid(row=4, column=1, padx=10, pady=10) + # 太字オプション + tk.Label(self.character_settings_window, text="スタイル:", bg="peach puff").grid(row=5, column=0, padx=10, pady=10, sticky="w") + self.font_style_var = tk.StringVar(value=self.character_list[self.character_index]["style"]) + tk.Radiobutton(self.character_settings_window, text="なし", bg="peach puff", variable=self.font_style_var, value="normal").grid(row=5, column=1, padx=10, pady=10) + tk.Radiobutton(self.character_settings_window, text="太字", bg="peach puff", variable=self.font_style_var, value="bold").grid(row=5, column=2, padx=10, pady=10) + tk.Radiobutton(self.character_settings_window, text="斜体", bg="peach puff", variable=self.font_style_var, value="italic").grid(row=5, column=3, padx=10, pady=10) + # 文字色オプション + self.text_color_label = tk.Label(self.character_settings_window,text="文字色選択", font=("メイリオ", 12, "bold"), justify="left") + self.text_color_label.grid(row=6, column=0, padx=10, pady=10, sticky="w") + # 文字色ボタン + tk.Button(self.character_settings_window, text="文字の色", command=lambda: self.change_text_color(True)).grid(row=6, column=1, padx=10, pady=10) + # 縁の色ボタン + tk.Button(self.character_settings_window,text="文字のフチの色",command=lambda: self.change_text_color(False)).grid(row=6, column=2, padx=10, pady=10, sticky="w") + # 縁のパターン + tk.Label(self.character_settings_window, text="文字のフチのパターン:", bg="peach puff").grid(row=7, column=0, padx=10, pady=10, sticky="w") + self.text_edge_var = tk.IntVar(value=self.character_list[self.character_index]["edge"]) + tk.Spinbox(self.character_settings_window, from_=0, to=6, textvariable=self.text_edge_var, width=4, command=lambda :self.rewrite_dict()).grid(row=7, column=1, padx=10, pady=10) + # テキスト位置 + self.text_position_var = tk.IntVar(value=self.character_list[self.character_index]["position"]) + tk.Label(self.character_settings_window, text="テキスト位置:", bg="peach puff").grid(row=8, column=0, padx=10, pady=10, sticky="w") + tk.Spinbox(self.character_settings_window, from_=0, to=100, textvariable=self.text_position_var, width=4, increment=5, command=lambda :self.rewrite_dict()).grid(row=8, column=1, padx=10, pady=10) + tk.Label(self.character_settings_window, text="%(下から)", bg="peach puff").grid(row=8, column=2, padx=10, pady=10, sticky="w") + char_button_frame = tk.Frame(self.character_settings_window, bg="orange") + char_button_frame.grid(row= 9, column= 0, columnspan=4, padx= 10, pady= 10, sticky="news") + # button + tk.Button(char_button_frame, text="追加", font=("メイリオ", 12, "bold"), bg="dark green", fg="white", command=lambda: self.add_char()).grid(row=0, column=0, padx=10, pady=10) + char_button_frame.grid_columnconfigure(1, weight=1) + tk.Button(char_button_frame, text="削除", font=("メイリオ", 12, "bold"), bg="red", fg="white", command=lambda: self.delete_char()).grid(row=0, column=2, padx=10, pady=10) + char_button_frame.grid_columnconfigure(3, weight=1) + tk.Button(char_button_frame, text="保存", font=("メイリオ", 12, "bold"), bg="blue", fg="white", command=lambda: self.save_character_data()).grid(row=0, column=4, padx=10, pady=10) + self.refresh_character_settings_window() + + def rewrite_dict(self): + self.character_list[self.character_index]["size"] = self.font_size_var.get() + self.character_list[self.character_index]["edge"] = self.text_edge_var.get() + self.character_list[self.character_index]["position"] = self.text_position_var.get() + + def refresh_character_settings_window(self): + self.character_index_label.config(text=f"{self.character_index + 1} / {self.total_char_num}") + self.name_canvas.delete("all") + self.name_canvas.create_text(232, 25, text=self.character_list[self.character_index]["name"], font=(self.character_list[self.character_index]["font"], 25), fill="black", anchor="center") + self.font_canvas.delete("all") + self.font_canvas.create_text(115, 15, text=self.character_list[self.character_index]["font"], font=(self.character_list[self.character_index]["font"], 16), fill="black", anchor="center") + self.font_size_var = tk.IntVar(value=self.character_list[self.character_index]["size"]) + self.font_style_var = tk.StringVar(value=self.character_list[self.character_index]["style"]) + self.text_color_label.config(fg=self.character_list[self.character_index]["color"], bg=self.character_list[self.character_index]["color2"]) + self.text_edge_var = tk.IntVar(value=self.character_list[self.character_index]["edge"]) + self.text_position_var = tk.IntVar(value=self.character_list[self.character_index]["position"]) + # 新しい配置を行う + self.font_size_var = tk.IntVar(value=self.character_list[self.character_index]["size"]) + tk.Spinbox(self.character_settings_window, from_=5, to=80, textvariable=self.font_size_var, width=4, command=lambda :self.rewrite_dict()).grid(row=4, column=1, padx=10, pady=10) + self.font_style_var = tk.StringVar(value=self.character_list[self.character_index]["style"]) + tk.Radiobutton(self.character_settings_window, text="なし", bg="peach puff", variable=self.font_style_var, value="normal").grid(row=5, column=1, padx=10, pady=10) + tk.Radiobutton(self.character_settings_window, text="太字", bg="peach puff", variable=self.font_style_var, value="bold").grid(row=5, column=2, padx=10, pady=10) + tk.Radiobutton(self.character_settings_window, text="斜体", bg="peach puff", variable=self.font_style_var, value="italic").grid(row=5, column=3, padx=10, pady=10) + self.text_edge_var = tk.IntVar(value=self.character_list[self.character_index]["edge"]) + tk.Spinbox(self.character_settings_window, from_=0, to=6, textvariable=self.text_edge_var, width=4, command=lambda :self.rewrite_dict()).grid(row=7, column=1, padx=10, pady=10) + self.text_position_var = tk.IntVar(value=self.character_list[self.character_index]["position"]) + tk.Spinbox(self.character_settings_window, from_=0, to=100, textvariable=self.text_position_var, width=4, increment=5, command=lambda :self.rewrite_dict()).grid(row=8, column=1, padx=10, pady=10) + + def change_character_name(self): + if self.character_index == 0: + self.sound_effect(12) + return + new_character_name = simpledialog.askstring("キャラクター名", f"キャラクター# {self.character_index + 1}\nに設定するキャラクター名を入力してください", parent=self.character_settings_window) + if not new_character_name: # キャンセルや空入力の場合は処理を中断 + self.sound_effect(12) + return + self.character_list[self.character_index]["name"] = new_character_name + self.name_canvas.delete("all") + self.name_canvas.create_text(232, 25, text=self.character_list[self.character_index]["name"], font=(self.character_list[self.character_index]["font"], 25), fill="black", anchor="center") + + def add_char(self): + self.character_list[self.character_index]["style"] = self.font_style_var.get() + self.total_char_num = len(self.character_list) + new_character_name = simpledialog.askstring("キャラクター名", f"キャラクター# {self.total_char_num + 1}\nに設定するキャラクター名を入力してください", parent=self.character_settings_window) + if not new_character_name: # キャンセルや空入力の場合は処理を中断 + self.sound_effect(12) + return + self.character_list.append({"name": "default", "font": "メイリオ", "size": 30, "style": "bold", "color": "black", "color2": "white", "edge":3, "position": 10}) + self.character_index = self.total_char_num + self.character_list[self.character_index]["name"] = new_character_name + self.total_char_num = len(self.character_list) + self.refresh_character_settings_window() + + def delete_char(self): + if self.character_list == 0: + self.sound_effect(12) + return + self.sound_effect(6) + delete_result = messagebox.askyesno("確認", f"キャラクターNO.{self.character_index + 1}\n{self.character_list[self.character_index]['name']}を削除します。\nよろしいですか?", parent=self.character_settings_window) + if delete_result: + self.character_list.pop(self.character_index) + self.total_char_num = len(self.character_list) + self.character_index = max(min(self.character_index, self.total_char_num - 1), 0) + messagebox.showinfo("確認", f"{self.character_list[self.character_index]['name']}を削除しました。", parent=self.character_settings_window) + self.refresh_character_settings_window() + else: + messagebox.showinfo("確認", "削除を取り消しました。",parent=self.character_settings_window) + + def save_character_data(self): + self.character_list[self.character_index]["style"] = self.font_style_var.get() + try: + with open(self.json_path, "w", encoding="utf-8") as file: + json.dump(self.character_list, file, ensure_ascii=False, indent=4) + self.sound_effect(9) + self.character_settings_window.destroy() + except Exception as e: + messagebox.showinfo("エラー", str(e), parent=self) + print(str(e)) + print(self.character_list) + + def seek_char_button(self, seek_num): + self.character_list[self.character_index]["style"] = self.font_style_var.get() + self.total_char_num = len(self.character_list) + self.sound_effect(8) + self.character_index += seek_num + self.character_index = max(min(self.character_index, self.total_char_num - 1), 0) + self.refresh_character_settings_window() + + def select_font(self): + self.sound_effect(9) + parent_x = self.character_settings_window.winfo_x() + parent_y = self.character_settings_window.winfo_y() + self.font_window = tk.Toplevel(self.character_settings_window) + self.font_window.geometry(f"220x900+{parent_x}+{parent_y - 70}") + self.font_window.title("Select Font") + self.font_window.resizable(False, False) + self.font_window.attributes('-topmost', True) + self.font_window.grab_set() + tk.Label(self.font_window, text="フォントを選んで下さい", font=("Arial", 12, "bold")).pack(pady=10) + font_frame = tk.Frame(self.font_window) + font_frame.pack(padx=10, pady=10) + scrollbar = tk.Scrollbar(font_frame) + scrollbar.pack(side="right", fill="y") + font_listbox = tk.Listbox(font_frame, yscrollcommand=scrollbar.set, width=30, height=50) + font_listbox.pack(side="left", fill="both") + scrollbar.config(command=font_listbox.yview) + # 全角と半角のフォントリストを分離してソート + font_names = tkfont.families() + # 全角文字を含むかどうかを判定 + def contains_zenkaku(text): + return any('\u3000' <= char <= '\u9FFF' or '\uFF01' <= char <= '\uFF60' for char in text) + # 全角文字を含むフォントを抽出 + zenkaku_fonts = sorted([name for name in font_names if contains_zenkaku(name)]) + # 半角のみのフォントを抽出 + hankaku_fonts = sorted([name for name in font_names if not contains_zenkaku(name)]) + # 全角フォントを先に追加し、次に半角フォントを追加 + for font_name in zenkaku_fonts + hankaku_fonts: + if not font_name.startswith("@"): + font_listbox.insert("end", font_name) + # フォント選択時に選択内容を設定してウィンドウを閉じる + def on_font_select(event): + selected_font = font_listbox.get(font_listbox.curselection()) + self.character_list[self.character_index]["font"] = selected_font + self.name_canvas.delete("all") + self.name_canvas.create_text(232, 25, text=self.character_list[self.character_index]["name"], font=(selected_font, 25), fill="black", anchor="center") + self.font_canvas.delete("all") + self.font_canvas.create_text(115, 15, text=self.character_list[self.character_index]["font"], font=(self.character_list[self.character_index]["font"], 16), fill="black", anchor="center") + self.sound_effect(9) + self.font_window.destroy() + # self.refresh_character_settings_window() + font_listbox.bind("<>", on_font_select) + self.wait_window(self.font_window) + + def change_text_color(self, foreground_color): + self.sound_effect(9) + color = colorchooser.askcolor(title="色を選択", parent=self.character_settings_window) + if color[1]: + color_string = color[1] + if foreground_color: + self.character_list[self.character_index]["color"] = color_string + self.text_color_label.config(fg=color_string) + else: + self.character_list[self.character_index]["color2"] = color_string + self.text_color_label.config(bg=color_string) + + def open_settings_window(self): + self.sound_effect(9) + geometry = self.geometry() + plot = geometry.split("+") + x, y = int(plot[1]), int(plot[2]) + settings_window = tk.Toplevel(self, bg="light cyan") + settings_window.geometry(f"366x360+{x+322}+{y+190}") + settings_window.resizable(False, False) + settings_window.transient(self) + settings_window.grab_set() + settings_window.title("設定") + + tk.Label(settings_window, text="表示画面:", bg="light cyan").grid(row=0, column=0, padx=10, pady=10) + full_screen_var = tk.BooleanVar(value=self.full_screen) + radio_window = tk.Radiobutton(settings_window, text="Window", bg="light cyan", variable=full_screen_var, value=False) + radio_window.grid(row=0, column=1, padx=10, pady=10) + radio_play_window = tk.Radiobutton(settings_window, text="Full Screen", bg="light cyan", variable=full_screen_var, value=True) + radio_play_window.grid(row=0, column=2, padx=10, pady=10) + tk.Label(settings_window, text="声の間隔:", bg="light cyan").grid(row=1, column=0, padx=10, pady=10) + voice_interval_var = tk.IntVar(value=self.voice_interval) + interval_spinbox = tk.Spinbox(settings_window, from_=100, to=2000, increment=100, width=5, textvariable=voice_interval_var) + interval_spinbox.grid(row=1, column=1, padx=10, pady=10) + tk.Label(settings_window, text="ミリ秒", bg="light cyan").grid(row=1, column=2, padx=10, pady=10, sticky="w") + line_break_var = tk.IntVar(value=self.line_break) + tk.Label(settings_window, text="一行の最大文字数:", bg="light cyan").grid(row=2, column=0, padx=10, pady=10) + tk.Spinbox(settings_window, from_=10, to=100, textvariable=line_break_var, width=4).grid(row=2, column=1, padx=10, pady=10) + sec_per_char_var = tk.IntVar(value=self.sec_per_char) + tk.Label(settings_window, text="一文字あたりの表示秒数:", bg="light cyan").grid(row=3, column=0, padx=10, pady=10) + tk.Spinbox(settings_window, from_=50, to=1000, textvariable=sec_per_char_var, width=6, increment=50).grid(row=3, column=1, padx=10, pady=10) + tk.Label(settings_window, text="ミリ秒", bg="light cyan").grid(row=3, column=2, padx=10, pady=10, sticky="w") + tk.Label(settings_window, text="CUT#1のBGMをデフォルトに:", bg="light cyan").grid(row=4, column=0, padx=10, pady=10) + default_bgm_var = tk.BooleanVar(value=self.default_bgm) + tk.Radiobutton(settings_window, text="ON", bg="light cyan", variable=default_bgm_var, value=True).grid(row=4, column=1, padx=10, pady=10) + tk.Radiobutton(settings_window, text="OFF", bg="light cyan", variable=default_bgm_var, value=False).grid(row=4, column=2, padx=10, pady=10) + tk.Label(settings_window, text="フォントサイズ自働調整:", bg="light cyan").grid(row=5, column=0, padx=10, pady=10) + print(type(self.adjust_font_size)) + adjust_font_size_var = tk.BooleanVar(value=self.adjust_font_size) + tk.Radiobutton(settings_window, text="ON", bg="light cyan", variable=adjust_font_size_var, value=True).grid(row=5, column=1, padx=10, pady=10) + tk.Radiobutton(settings_window, text="OFF", bg="light cyan", variable=adjust_font_size_var, value=False).grid(row=5, column=2, padx=10, pady=10) + tk.Button(settings_window,text="改行ポイント文字", command=lambda: self.change_punctuation_marks(settings_window, line_break_label)).grid(row=6, column=0, padx=10, pady=10) + line_break_label = tk.Label(settings_window, text=self.punctuation_marks, bg="light cyan") + line_break_label.grid(row=6, column=1, columnspan=2, padx=10, pady=10, sticky="w") + tk.Button(settings_window, text="適用", font=("メイリオ", 12, "bold"), command=lambda: self.apply_settings\ + (settings_window, full_screen_var, voice_interval_var, line_break_var, sec_per_char_var, default_bgm_var, adjust_font_size_var))\ + .grid(row=7, column=0, columnspan=3, padx=50, pady= 10) + + def change_punctuation_marks(self, settings_window, line_break_label): + default_text = self.punctuation_marks + user_input = simpledialog.askstring("改行ポイント文字", "ここで設定した文字の後でセリフが改行されやすくなります。\n(セリフに全角スペースをいれるとそこで確実に改行されます。)", initialvalue=default_text, parent=settings_window) + if not user_input or default_text == user_input: + return + self.punctuation_marks = user_input + line_break_label.config(text= self.punctuation_marks) + self.sound_effect(10) + + def apply_settings(self, settings_window, full_screen_var, voice_interval_var, line_break_var, sec_per_char_var, default_bgm_var, adjust_font_size_var): + self.sound_effect(9) + self.full_screen = full_screen_var.get() + self.voice_interval = voice_interval_var.get() + self.line_break = line_break_var.get() + self.sec_per_char = sec_per_char_var.get() + self.default_bgm = default_bgm_var.get() + self.adjust_font_size = adjust_font_size_var.get() + self.sound_effect(10) + settings_window.destroy() + + def select_play_mode(self): + self.sound_effect(9) + geometry = self.geometry() + plot = geometry.split("+") + x, y = int(plot[1]), int(plot[2]) + play_mode_window = tk.Toplevel(self, bg="light cyan") + play_mode_window.geometry(f"366x570+{x+322}+{y+85}") + play_mode_window.resizable(False, False) + play_mode_window.transient(self) + play_mode_window.grab_set() + play_mode_window.title("プレイモード設定") + play_mode_window.drop_target_register(DND_FILES) + play_mode_window.dnd_bind('<>', lambda e: self.drop_image_folder(e)) + + play_mode_var = tk.IntVar(value=self.play_mode[self.current_story_index]) + scenario_button = tk.Radiobutton(play_mode_window, text="シナリオモード", font=("メイリオ", 13, "bold"), bg="light cyan", fg="dark green", variable=play_mode_var, value=0) + scenario_button.grid(row=0, column=0, columnspan=3, padx=10, pady=5) + + tk.Label(play_mode_window, text="番号順に音声とテキストを再生。\nファイル名に番号の無い音声は再生しません。", bg="light cyan", fg="dark green").grid(row=1, column=0, columnspan=3) + + random_voice_button = tk.Radiobutton(play_mode_window, text="ランダムボイスモード", font=("メイリオ", 13, "bold"), bg="light cyan", fg="dark orange3", variable=play_mode_var, value=1) + random_voice_button.grid(row=2, column=0, columnspan=3, padx=10, pady=5) + + tk.Label(play_mode_window, text="Voiceフォルダ内の音声からランダムに再生。\n番号の無い音声も対象です。テキスト表示はしません。", bg="light cyan", fg="dark orange3").grid(row=3, column=0, columnspan=3) + + radio_normal = tk.Radiobutton(play_mode_window, text="ランダムイメージモード", font=("メイリオ", 13, "bold"), bg="light cyan", fg="red", variable=play_mode_var, value=2) + radio_normal.grid(row=4, column=0, columnspan=3, padx=10, pady=5) + + tk.Label(play_mode_window, text="ランダムイメージフォルダ内の画像・動画をランダムに表示。\n音声はCUT#1のVoiceフォルダからランダムに再生。テキスト表示はしません。", bg="light cyan", fg="red").grid(row=5, column=0, columnspan=3) + + tk.Button(play_mode_window,text="ランダムイメージフォルダ", command=lambda: self.select_random_image(play_mode_window)).grid(row=6, column=0, padx=10, pady=(10, 0)) + tk.Label(play_mode_window, text="画像・動画の入ったフォルダを\nこのウインドウにドロップ", bg="light cyan").grid(row=6, column=1, columnspan=2, pady=(10, 0)) + self.path_label = tk.Label(play_mode_window, text=self.random_image_folder[self.current_story_index], bg="white", width= 48, wraplength=330, height=3, anchor="nw", justify="left") + self.path_label.grid(row=7, column=0, columnspan=3, padx=10, pady=(5, 10), sticky="w") + + random_voice_num_var = tk.IntVar(value=self.random_voice_num[self.current_story_index]) + tk.Label(play_mode_window, text="ランダムボイス・イメージモード時\n再生する声の数:", bg="light cyan").grid(row=8, column=0, columnspan=1, padx=10, pady=10) + tk.Spinbox(play_mode_window, from_=1, to=8, textvariable=random_voice_num_var, width=4).grid(row=8, column=1, columnspan=2, padx=10, pady=10) + + tk.Label(play_mode_window, text="イメージの表示順:", bg="light cyan").grid(row=9, column=0, padx=10, pady=10) + random_order_var = tk.BooleanVar(value=self.random[self.current_story_index]) + radio_normal = tk.Radiobutton(play_mode_window, text="通常", bg="light cyan", variable=random_order_var, value=False) + radio_normal.grid(row=9, column=1, padx=10, pady=10) + radio_random = tk.Radiobutton(play_mode_window, text="ランダム", bg="light cyan", variable=random_order_var, value=True) + radio_random.grid(row=9, column=2, padx=10, pady=10) + + tk.Label(play_mode_window, text="画像最小表示時間:", bg="light cyan").grid(row=10, column=0, padx=10, pady=10) + min_display_var = tk.IntVar(value=self.min_display[self.current_story_index]) + min_display_spinbox = tk.Spinbox(play_mode_window, from_=1, to=30, increment=1, width=5, textvariable=min_display_var) + min_display_spinbox.grid(row=10, column=1, padx=10, pady=10) + tk.Label(play_mode_window, text="秒", bg="light cyan").grid(row=10, column=2, padx=10, pady=10, sticky="w") + + tk.Button(play_mode_window, text="適用", font=("メイリオ", 12, "bold"), command=lambda: self.apply_play_mode_settings(play_mode_window, play_mode_var, random_voice_num_var, random_order_var, min_display_var)).grid(row=11, column=0, columnspan=3, padx=50, pady= 10) + + def apply_play_mode_settings(self, play_mode_window, play_mode_var, random_voice_num_var, random_order_var, min_display_var): + self.sound_effect(9) + self.play_mode[self.current_story_index] = play_mode_var.get() + self.random_voice_num[self.current_story_index] = random_voice_num_var.get() + self.random[self.current_story_index] = random_order_var.get() + self.min_display[self.current_story_index] = min_display_var.get() + self.show_playmode_button() + self.cut_modification = True + self.save_cutdata_to_story_txt() + self.sound_effect(10) + play_mode_window.destroy() + + def show_playmode_button(self): + text = ["シナリオモード", "ランダムボイス", "ランダムイメージ"] + color = ["dark green", "dark orange3", "red"] + self.play_mode_button.config(text= text[self.play_mode[self.current_story_index]], bg= color[self.play_mode[self.current_story_index]]) + + def select_random_image(self, play_mode_window,): + file_path = filedialog.askdirectory(title=f"ランダム表示する画像・動画フォルダを選んでください。", parent=play_mode_window) + if file_path: + file_path = file_path.replace("\\", "/") + self.random_image_folder[self.current_story_index] = file_path + self.path_label.config(text= file_path) + self.sound_effect(10) + + def drop_image_folder(self, event, ): + print(f"ドロップされたデータ: {event.data}") # デバッグ用 + dropped_path = event.data.strip("{}") + path = os.path.abspath(dropped_path).replace('\\', '/') + if not os.path.isdir(path): + self.sound_effect(12) + return + else: + self.random_image_folder[self.current_story_index] = path + self.path_label.config(text= path) + self.sound_effect(10) + +# # ------ Main ------- + +if __name__ == "__main__": + app = VoiceStoryPlayer() + app.mainloop()