0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google ColabでMIDIファイルを文字起こしするPythonプログラム解説

Posted at

概要(Overview)

このプログラムは、Google Colab上でMIDIファイルをアップロードすると、全トラックのイベントを読み取り、テキストとして出力・表示・保存するツールです。
音楽の打ち込みデータ(note_on, note_off, control_changeなど)を人間が読める形式で確認できるため、楽曲解析・作曲研究・MIDIデータ解析に利用できます。


処理の流れ(Flow)

  1. ライブラリの準備
    Colab上で mido をインストールします。
    MIDOはPythonでMIDIデータを扱うための標準ライブラリで、トラック情報やノート、テンポ、プログラムチェンジなどを簡単に取得できます。

    !pip install mido
    
  2. MIDIファイルのアップロード
    Google Colabの files.upload() 機能を利用し、ローカルからMIDIファイルをアップロードします。
    実行するとアップロードボタンが表示され、ファイルを選択できます。

    uploaded = files.upload()
    midi_path = list(uploaded.keys())[0]
    
  3. MIDIデータの読み込み
    アップロードしたファイルを mido.MidiFile() で読み込み、トラック構成を解析します。

    mid = mido.MidiFile(midi_path)
    
  4. テキスト化処理(Transcription)
    各トラックを順に走査し、各イベント(例:note_on, note_off, control_change)をテキストとして記録します。
    同時に print() で逐次出力するため、Colabセル上でもリアルタイムに確認可能です。

    for i, track in enumerate(mid.tracks):
        header = f"\n--- Track {i}: {track.name} ---\n"
        for msg in track:
            print(msg)
    
  5. テキストファイルへの保存
    解析結果を "midi_transcription.txt" に書き込み、ダウンロードできるようにします。

    with open(output_txt, "w", encoding="utf-8") as f:
        f.write(text_output)
    
  6. Colab上で整形表示(HTML形式)
    IPython.displayHTML を利用して、MIDIイベントをモノスペースフォントで整形表示します。
    これにより、ノートやテンポなどの情報を見やすく確認できます。

    html_output = text_output.replace("\n", "<br>")
    display(HTML(f"<div style='font-family:monospace; white-space:pre;'>{html_output}</div>"))
    
  7. テキストファイルのダウンロード
    最後に files.download() により、自動的にテキストファイルをローカルへ保存できます。


出力例(Example Output)

--- Track 0: ---
<meta message track_name name='MIDI Sample'>
<meta message set_tempo tempo=500000 time=0>
<message note_on channel=0 note=60 velocity=90 time=0>
<message note_off channel=0 note=60 velocity=0 time=480>
<message note_on channel=0 note=64 velocity=90 time=0>
<message note_off channel=0 note=64 velocity=0 time=480>


#---------------------------------------------
# 必要ライブラリのインストール / Install required libraries
#---------------------------------------------
!pip install mido

#---------------------------------------------
# ライブラリのインポート / Import libraries
#---------------------------------------------
import mido
from google.colab import files
from IPython.display import display, HTML

#---------------------------------------------
# ① MIDIファイルをアップロード / Upload MIDI file
#---------------------------------------------
print("MIDIファイルをアップロードしてください / Please upload a MIDI file")
uploaded = files.upload()
midi_path = list(uploaded.keys())[0]
print("✅ Uploaded:", midi_path)

#---------------------------------------------
# ② MIDIデータを読み込み / Read MIDI file
#---------------------------------------------
mid = mido.MidiFile(midi_path)
print("✅ MIDI file loaded successfully")

#---------------------------------------------
# ③ テキスト化処理 / Transcribe MIDI data to text
#---------------------------------------------
output_txt = "midi_transcription.txt"
text_output = ""

for i, track in enumerate(mid.tracks):
    header = f"\n--- Track {i}: {track.name} ---\n"
    text_output += header
    print(header)
    for msg in track:
        line = str(msg)
        text_output += line + "\n"
        print(line)

#---------------------------------------------
# ④ テキストファイルに保存 / Save as text file
#---------------------------------------------
with open(output_txt, "w", encoding="utf-8") as f:
    f.write(text_output)
print(f"\n✅ Transcription saved as {output_txt}")

#---------------------------------------------
# ⑤ Google Colab上で整形表示 / Display nicely in Colab
#---------------------------------------------
html_output = text_output.replace("\n", "<br>")
display(HTML(f"<div style='font-family:monospace; white-space:pre;'>{html_output}</div>"))

#---------------------------------------------
# ⑥ テキストファイルをダウンロード / Download transcription file
#---------------------------------------------
files.download(output_txt)

#---------------------------------------------
# 日本語説明:
# - Colab上でMIDIイベントをprint関数で逐次表示し、最後に整形してHTML表示します。
# - 同時にテキストファイルとして保存・ダウンロード可能です。
#
# English explanation:
# - Prints each MIDI event to Colab output and displays formatted text at the end.
# - Also saves and downloads as a text file.
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?