mp3からテキスト作成

PythonでMP3ファイルの最初の任意の秒数を削除するには、pydubライブラリを使うのが簡単です。以下に、任意の秒数をカットした新しいMP3ファイルを作成するコードを示します。
 ---

from pydub import AudioSegment

# 設定
input_file = "input.mp3"        # 入力ファイル名
output_file = "output.mp3"      # 出力ファイル名
cut_seconds = 5                 # 最初の何秒をカットするか(ここでは5秒)

# 読み込み
audio = AudioSegment.from_mp3(input_file)

# カット(ミリ秒単位)
start_ms = cut_seconds * 1000
cut_audio = audio[start_ms:]

# 書き出し
cut_audio.export(output_file, format="mp3")

print(f"{cut_seconds}秒をカットした音声を保存しました: {output_file}")

---
cut_seconds を変更すれば、削除する秒数を自由に設定できます。

input_file と output_file のパスは適宜書き換えてください。

音質設定(ビットレートなど)を指定したい場合は、export() に bitrate="192k" などの引数を追加できます。


***

from pydub import AudioSegment

# 設定
input_file = "input.mp3"        # 入力ファイル名
output_file = "output.mp3"      # 出力ファイル名
cut_seconds = 5                 # 最初の何秒をカットするか

# 読み込み
audio = AudioSegment.from_mp3(input_file)

# カット(ミリ秒単位)
start_ms = cut_seconds * 1000
cut_audio = audio[start_ms:]

# 書き出し(ビットレート指定)
cut_audio.export(output_file, format="mp3", bitrate="192k")

print(f"{cut_seconds}秒をカットして192kbpsで保存しました: {output_file}")

**

必要に応じて、他のビットレート(例:128k, 256k, 320k)にも変更可能です。
他に指定したい設定があれば教えてください。

**

はい、ffmpeg でも MP3の最初の任意の秒数を削除(=トリミング)することができます。Pythonからでも、コマンドラインからでも実行可能です。

✅ ffmpeg コマンドラインでの方法(例:最初の5秒を削除)
bash
コピーする
編集する
ffmpeg -ss 5 -i input.mp3 -acodec copy output.mp3
🔍 解説
-ss 5:5秒から再生を開始(=最初の5秒をカット)

-i input.mp3:入力ファイル

-acodec copy:再エンコードせずにコピー(速くて音質も劣化しません)

**

✅ Pythonからffmpegを使う方法(subprocessを利用)
python
コピーする
編集する
import subprocess

input_file = "input.mp3"
output_file = "output.mp3"
cut_seconds = 5

command = [
    "ffmpeg",
    "-ss", str(cut_seconds),
    "-i", input_file,
    "-acodec", "copy",
    output_file
]

subprocess.run(command)
print(f"{cut_seconds}秒をカットして保存しました: {output_file}")
✅ 注意点
-acodec copy を使うと高速ですが、正確なカット位置(ミリ秒単位)にはならないことがあります(キーフレーム単位)。

より正確なカットが必要な場合は 再エンコード を使う必要があります:

bash
コピーする
編集する
ffmpeg -ss 5 -i input.mp3 -t 30 -b:a 192k output.mp3
この場合:

-t 30 は30秒間切り出す(任意)

-b:a 192k はビットレート指定(例:192kbps)

✅ まとめ
方法 高速か 正確か 音質劣化
-acodec copy ◎(速い) △(少しズレる) なし(再エンコードしない)
再エンコードあり △(遅い) ◎(正確) あり(再エンコード)

どちらを使うかは用途によって決めるとよいです。Pythonでどちらの方法でも書けます。希望の形式があれば教えてください。

以上h
https://chatgpt.com/c/688cb6d5-5d94-800c-a671-9c6160e5284e
MP3秒数削除コード


--------------
from pydub import AudioSegment
import os

# 設定
input_file = "input.mp3"         # 入力ファイル名
cut_seconds = 5                  # 最初の何秒をカットするか

# 自動で出力ファイル名を設定
base_name = os.path.splitext(input_file)[0]
output_file = base_name + "_no_intro.mp3"

# 読み込み
audio = AudioSegment.from_mp3(input_file)

# カット(ミリ秒単位)
start_ms = cut_seconds * 1000
cut_audio = audio[start_ms:]

# 書き出し(ビットレート指定)
cut_audio.export(output_file, format="mp3", bitrate="192k")

print(f"{cut_seconds}秒をカットして保存しました: {output_file}")
***

このコードなら、input_file の名前を変更しても、自動で *_no_intro.mp3 という形で保存されます。

他にも _trimmed, _cut, _start5s など、命名ルールを変えたい場合も調整できます。希望があればお知らせください。

***
output_file = base_name + "_cut_start"+cut_seconds+"s " 
のようにして下さい。


ChatGPT:
はい、cut_seconds をファイル名に組み込んで、
たとえば input_cut_start5s.mp3 のような出力ファイル名にするには、cut_seconds を文字列として結合する必要があります。

✅ 修正コード(cut_seconds をファイル名に入れる)
python
コピーする
編集する
from pydub import AudioSegment
import os

# 設定
input_file = "input.mp3"        # 入力ファイル名
cut_seconds = 5                 # 最初の何秒をカットするか

# 出力ファイル名を自動生成(例: input_cut_start5s.mp3)
base_name = os.path.splitext(input_file)[0]
output_file = f"{base_name}_cut_start{cut_seconds}s.mp3"

# 音声を読み込み
audio = AudioSegment.from_mp3(input_file)

# カット(ミリ秒単位)
start_ms = cut_seconds * 1000
cut_audio = audio[start_ms:]

# 書き出し(ビットレート指定)
cut_audio.export(output_file, format="mp3", bitrate="192k")

print(f"{cut_seconds}秒をカットして保存しました: {output_file}")
✅ 出力例
input.mp3 → input_cut_start5s.mp3

lesson01.mp3 → lesson01_cut_start10s.mp3(cut_seconds=10の場合)

ファイル名のフォーマットをもっと変えたい場合(例:start5sec_trimmed.mp3など)、いつでも言ってください。

---
HORIZONのリスニング音声を文字に変換する

この処理をしたmp3をテキストに変換する。

#a-whisper-mp3totxt.py
import whisper
import os

# === ファイル設定 ===
mp3_file = "1-33 Unit_2_Mini_Activity_Listen_2.mp3__no_intro.mp3"
output_txt = os.path.splitext(mp3_file)[0] + ".txt"

# === Whisperモデルの読み込み ===
model = whisper.load_model("small")  # "base" や "medium" もOK

# === 英文音声の認識(英語指定)===
print("音声を文字起こし中...")
result = model.transcribe(mp3_file, language="en")

# === センテンスごとに改行して保存 ===
with open(output_txt, "w", encoding="utf-8") as f:
    for segment in result["segments"]:
        sentence = segment["text"].strip()
        if sentence:
            f.write(sentence + "\n")

print(f"✅ センテンスごとに改行したテキストを保存しました: {output_txt}")


----
ディレクトリ内の複数の.mp3を一括処理版
import whisper
import os
import glob

# === ディレクトリの指定(任意のディレクトリに変更可)===
input_dir = "input_mp3"  # ← MP3ファイルがあるディレクトリ名
output_dir = "output_txt"  # テキストファイルの保存先

# 出力先ディレクトリがなければ作成
os.makedirs(output_dir, exist_ok=True)

# === Whisperモデルの読み込み ===
model = whisper.load_model("small")  # "base" や "medium" も使用可

# === mp3ファイルを一括取得 ===
mp3_files = glob.glob(os.path.join(input_dir, "*.mp3"))

if not mp3_files:
    print("⚠️ 指定されたディレクトリに .mp3 ファイルが見つかりません。")
else:
    for mp3_file in mp3_files:
        base_name = os.path.splitext(os.path.basename(mp3_file))[0]
        output_txt = os.path.join(output_dir, base_name + ".txt")

        print(f"▶️ 処理中: {mp3_file}")

        # === 音声認識(英語指定)===
        result = model.transcribe(mp3_file, language="en")

        # === センテンスごとに改行して保存 ===
        with open(output_txt, "w", encoding="utf-8") as f:
            for segment in result["segments"]:
                sentence = segment["text"].strip()
                if sentence:
                    f.write(sentence + "\n")

        print(f"✅ 保存完了: {output_txt}")

print("🎉 すべてのファイルの処理が完了しました。")

---

補足設定
input_mp3: MP3ファイルを入れるフォルダ(任意の名前でOK)

output_txt: 出力ファイルの保存先(自動作成されます)

ファイル名が sample.mp3 の場合、出力は output_txt/sample.txt になります

📁 フォルダ構成の例
コピーする
編集する
project_folder/
├─ input_mp3/
│   ├─ file1.mp3
│   ├─ file2.mp3
├─ output_txt/
│   ├─ file1.txt
│   ├─ file2.txt
├─ your_script.py
必要に応じて language="en" を language="ja" にすれば日本語音声も処理できます。
ご希望あればGUI化や進行状況の表示もできます。

---
以下も参考にしたい。
GUI化や進行状況の表示バージョンをお願いします。


ChatGPT:
以下に、GUI化(Tkinter)+進行状況の表示(プログレスバー付き)バージョンを提供します。
これにより、MP3ファイルの一括文字起こしがGUI操作で可能になります。

✅ 必要なライブラリ
Whisper(openai-whisper)インストール済みであること

GUIはPython標準の tkinter を使用

tqdm は進行状況用ライブラリ(使用せずGUIのプログレスバーで代用)

✅ GUIコード(フォルダ選択・音声ファイル処理・進捗表示)
python
コピーする
編集する
import whisper
import os
import glob
import threading
import tkinter as tk
from tkinter import filedialog, messagebox, ttk

class WhisperTranscriberApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Whisper MP3一括文字起こし")
        self.root.geometry("500x200")
        self.create_widgets()
        self.model = whisper.load_model("small")  # 必要に応じて変更

    def create_widgets(self):
        self.label = tk.Label(self.root, text="MP3ファイルのあるフォルダを選択してください")
        self.label.pack(pady=10)

        self.select_button = tk.Button(self.root, text="フォルダを選択", command=self.select_folder)
        self.select_button.pack()

        self.progress = ttk.Progressbar(self.root, orient="horizontal", length=400, mode="determinate")
        self.progress.pack(pady=20)

        self.status = tk.Label(self.root, text="")
        self.status.pack()

    def select_folder(self):
        folder = filedialog.askdirectory()
        if folder:
            threading.Thread(target=self.process_folder, args=(folder,), daemon=True).start()

    def process_folder(self, folder):
        self.select_button.config(state="disabled")
        self.status.config(text="Whisperモデル読み込み中...")
        output_dir = os.path.join(folder, "output_txt")
        os.makedirs(output_dir, exist_ok=True)

        mp3_files = glob.glob(os.path.join(folder, "*.mp3"))
        total = len(mp3_files)

        if total == 0:
            messagebox.showwarning("ファイルなし", "指定されたフォルダにMP3ファイルが見つかりません。")
            self.select_button.config(state="normal")
            return

        self.progress["maximum"] = total
        self.status.config(text=f"{total} 件のファイルを処理中...")

        for i, mp3_file in enumerate(mp3_files, 1):
            base_name = os.path.splitext(os.path.basename(mp3_file))[0]
            output_txt = os.path.join(output_dir, base_name + ".txt")

            self.status.config(text=f"[{i}/{total}] {os.path.basename(mp3_file)} を文字起こし中...")
            result = self.model.transcribe(mp3_file, language="en")

            with open(output_txt, "w", encoding="utf-8") as f:
                for segment in result["segments"]:
                    sentence = segment["text"].strip()
                    if sentence:
                        f.write(sentence + "\n")

            self.progress["value"] = i
            self.root.update_idletasks()

        self.status.config(text="✅ すべてのファイルの処理が完了しました。")
        messagebox.showinfo("完了", "すべてのMP3ファイルを文字起こししました。")
        self.select_button.config(state="normal")


if __name__ == "__main__":
    root = tk.Tk()
    app = WhisperTranscriberApp(root)
    root.mainloop()
💡 このアプリの特徴
項目 内容
入力 MP3が含まれる任意のフォルダ
出力 フォルダ内に output_txt/ を自動生成して保存
モデル small を使用(適宜 base, medium などに変更可能)
言語 英語(language="en")← 必要に応じて "ja" に変更
UI操作 フォルダ選択 → 自動処理開始
進行状況表示 プログレスバーとステータスで可視化

🔄 応用
日本語音声:language="ja" にする

モデル変更:whisper.load_model("medium") などに変更

フォルダ選択で output/ ディレクトリを外に出すことも可能

必要であれば .exe 化(PyInstaller)や、翻訳付き保存にも対応可能です。ご希望があればどうぞ。

Splitting MP4 Files by Time Using FFmpeg

FFmpegによりMP4ファイルを時間で分割
(Splitting MP4 Files by Time Using FFmpeg)

●10分(600秒)ごとに動画を分割
>ffmpeg -i input.mp4 -c copy -map 0 -segment_time 600 -f segment output_%03d.mp4

オプションの説明:
-i input.mp4:入力ファイル
-c copy:再エンコードせず高速に処理(画質劣化なし)
-map 0:すべてのストリームを保持
-segment_time 600:600秒(10分)ごとに分割
-f segment:セグメント形式で出力
output_%03d.mp4:出力ファイル名(例:output_000.mp4, output_001.mp4, ...)

次のように、時間範囲を指定して分割することも可能
>ffmpeg -i input.mp4 -ss 00:00:00 -t 00:10:00 -c:v libx264 -c:a aac output1.mp4

●最初から28分38秒を切り出す(
002838切り出す)

>ffmpeg -i input.mp4 -ss 00:00:00 -t 00:28:38 -c copy output_trimmed.mp4

・正確に「ぴったり00:28:38まで」で切りたい場合は、以下のように、「再エンコードあり」にします
>ffmpeg -i input.mp4 -ss 00:00:00 -t 00:28:38 -c:v libx264 -c:a aac output_trimmed.mp4

-i input.mp4:元の動画ファイル名
-ss 00:00:00:開始位置(今回は最初から)
-t 00:28:38:切り出す長さ(28分38秒)
-c copy:再エンコードせず高速処理(元画質そのまま)
output_trimmed.mp4:出力されるファイル名
-c:v libx264
ビデオ(映像)を H.264形式でエンコード(圧縮)する
libx264
FFmpeg が使う H.264 のエンコーダライブラリ
利点:
高い圧縮率と高画質
-c:a aac
意味:オーディオ(音声)を AAC(Advanced Audio Coding) 形式でエンコードする
aac は FFmpeg に内蔵されている AAC エンコーダ
利点:
MP4で標準的に使われる音声形式
MP3より効率的で高音質(同じビットレートなら)

・再エンコードを行うことで、表のようなメリットがあります
   -c copy(速さ)と libx264 / aac(正確さ・互換性)を使い分ける👆

項目 -c copy 使用時 libx264 / aac 使用時
処理速度 高速(コピー) やや遅い(再エンコード)
精度(時間) キーフレームに制限される 正確に指定時間で切り出せる
ファイル互換性 元のコーデックに依存 非常に高い(多くのデバイス対応)

英単語の音声ファイルから音声に含まれる単語リストと個々の単語の音声ファイルを作成する

英単語の音声ファイル(ample.mp3)から音声に含まれる単語リスト(sample.txt  )と個々の単語の音声ファイル(1-man.mp3など)を作成する。

■ファイル構造

📂 プロジェクトフォルダ
│── 📄 mp3_words_note.py  # Pythonコード(音声を処理するスクリプト)
│── 🎵 sample.mp3    # 入力ファイル(音声ファイル<複数の単語を含む>)
│── 📄 sample.txt       # 出力ファイル(抽出した単語リスト)
│── 📂 sample_音声/  # 出力ディレクトリ(個々に分割した音声ファイルの保存)
│    ├── 🎵 1-man.mp3
│    ├── 🎵 2-people.mp3
│    ├── 🎵 3-life.mp3
│    ├── 🎵 4-child.mp3
│    ├── 🎵 5-person.mp3

PS > tree /F /A
\---プロジェクトフォルダ
     |   mp3_words_note.py
     |   sample.mp3
     |   sample.txt
     \---sample_音声
              1-man.mp3
              2-people.mp3
              3-life.mp3
              4-child.mp3
              5-person.mp3
 
[実行]
プロジェクトフォルダに入り実行
>python mp3_words_note.py⏎

・出力ファイル(sample.txt)例
1,man
2,people
3,life
4,child
5,person
6,group
7,live
8,name
9,woman
10,member
11,boy
12,family
13,girl
14,unrecognized
15,student

・  'unrecognized'は認識できない単語を意味する。
・音声認識ができない場合、誤認識は手動で修正する。

[Tips]
PowerShellコマンドでディレクトリ内のファイルを番号順に表示する方法
PS \sample_音声> ls -Name | Sort-Object {[int]($_ -split '-')[0]}

Sort-Object を使って、ファイル名の左側の数字でソート 。
ポイント
{} の中は ブロック(スクリプトブロック) と呼ぶ。
$_ は パイプラインで流れてきた1つ1つの値(この場合はファイル名)。
-split '-' で ハイフン - で分割。
[0] で 分割した最初の部分(左側の数字)を取得。
[int] で 文字列から整数に変換。

全体の流れ
ls -Name でファイル名のリストを取得。
Sort-Object で、各ファイル名を - で分割。
[0] で左側の数字を取得し、[int] で整数化。
数値順にソート。

[コード例]mp3_words_note.py
注意
コード内の以下の値を適宜変更してください。音声データにより変更する必要があります。
min_silence_len=250,
silence_thresh=sound.dBFS - 10.5,
keep_silence=1000

---以下がpythonコード例
import os
import speech_recognition as sr
from pydub import AudioSegment
from pydub.silence import split_on_silence

# 一括でファイル名を定義
mp3_file = "sample.mp3"  # 英文のみの音声サンプル
basename = os.path.splitext(mp3_file)[0]  # basename="sample"
wav_file = "converted.wav"
txt_file = f"{basename}.txt" #sample.txt"

# MP3ファイルをWAVに変換
sound = AudioSegment.from_mp3(mp3_file)
sound.export(wav_file, format="wav")

# 無音を作成する関数
def generate_silence(duration_sec):
    return AudioSegment.silent(duration=duration_sec * 1000)# ミリ秒に変換

# 音声ファイルを無音部分で分割(無音部分で区切る)
def split_audio(file_path):
    sound = AudioSegment.from_wav(file_path)
    chunks = split_on_silence(
        sound,
        min_silence_len=250,
        silence_thresh=sound.dBFS - 10.5,
        keep_silence=1000
    )
    return chunks

# 音声認識の準備
recognizer = sr.Recognizer()
audio_chunks = split_audio(wav_file)# WAVファイルをチャンクごとに分割
recognized_words = []# 変換したテキスト(単語)を保存するリスト
# 各チャンクをテキストに変換
chunk_files = []# 生成されたチャンクファイルのリスト

# 各チャンクをテキストに変換
for i, chunk in enumerate(audio_chunks):
    chunk_filename = f"chunk{i+1}.wav"
    chunk.export(chunk_filename, format="wav")
    chunk_files.append(chunk_filename)
    
    with sr.AudioFile(chunk_filename) as source:
        audio = recognizer.record(source)
    
    # 音声をテキストに変換( 認識結果をリストに追加)
    try:
        text = recognizer.recognize_google(audio, language="en-US").strip()
        recognized_words.append(f"{i+1},{text}")
    except sr.UnknownValueError:
        recognized_words.append(f"{i+1},unrecognized")
    except sr.RequestError as e:
        print(f"Googleサービスへのリクエストに失敗しました; {e}")

# TXTファイルに書き込む
with open(txt_file, "w", encoding="utf-8") as txtfile:
    for line in recognized_words:
        txtfile.write(line + "\n")
print(f"認識結果を {txt_file} に保存しました。")

# TXTファイルから単語リストを取得
word_dict = {}
with open(txt_file, "r", encoding="utf-8") as f:
    for line in f:
        parts = line.strip().split(",")
        if len(parts) == 2:
            word_dict[int(parts[0])] = parts[1]

# 出力ディレクトリの作成
output_dir = f"{basename}_音声" # 音声ファイルの保存ディレクトリ名 
os.makedirs(output_dir, exist_ok=True)

# 各チャンクをMP3に変換して保存
for i, chunk in enumerate(audio_chunks):
    word = word_dict.get(i+1, "unrecognized")
    mp3_filename = f"{i+1}-{word}.mp3"
    output_path = os.path.join(output_dir, mp3_filename) # ディレクトリに保存
    chunk.export(output_path, format="mp3") # チャンクをMP3として保存
    print(f"{output_path} に保存されました。")

# 一時ファイルの削除(生成されたWAVファイルを削除)
os.remove(wav_file)
for chunk_file in chunk_files:
    os.remove(chunk_file)

単語が書かれたファイルに発音記号を追加する

課題
ディレクトリ'tango'にある単語のファイル(words_list.txt)にアメリカ英語の発音記号(IPA)を追加してphonetic_list.txtとして書き出すpythonコード 

windows10
PS> python words_phonetic_symbols.py

pip install eng-to-ipa
を実行してライブラリをインストールする。

・ファイル構造:
tango/
  words_list.txt
  phonetic_list.txt

・words_list.txt:入力ファイル例
1,man
2,people
3,life
4,child
5,person

・phonetic_list.txt:出力ファイル例
1,man,mæn
2,people,ˈpipəl
3,life,laɪf
4,child,ʧaɪld
5,person,ˈpərsən

■python コード例

import eng_to_ipa as ipa
import os

def get_ipa(word):
    return ipa.convert(word, retrieve_all=False)

def add_ipa_to_words(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile:
        for line in infile:
            parts = line.strip().split(',')
            if len(parts) == 2:
                index, word = parts
                ipa_transcription = get_ipa(word.lower())
                outfile.write(f"{index},{word},{ipa_transcription}\n")

directory = "tango"
words_file = os.path.join(directory, "words_list.txt")
phonetic_file = os.path.join(directory, "phonetic_list.txt")

add_ipa_to_words(words_file, phonetic_file)
print("IPA追加完了: phonetic_list.txt に出力しました。")