| import os |
| import glob |
| import json |
| import struct |
| import subprocess |
| from pathlib import Path |
| import time |
|
|
| def get_ogg_opus_duration(filepath): |
| with open(filepath, 'rb') as f: |
| f.seek(0, 2) |
| file_size = f.tell() |
| |
| chunk_size = min(65536, file_size) |
| f.seek(file_size - chunk_size) |
| data = f.read(chunk_size) |
| |
| last_oggs_idx = data.rfind(b'OggS') |
| if last_oggs_idx == -1: |
| return 0 |
| |
| granule_bytes = data[last_oggs_idx+6 : last_oggs_idx+14] |
| granule_position = struct.unpack('<q', granule_bytes)[0] |
| |
| return int((granule_position / 48000.0) * 1000) |
|
|
| def test_concat(): |
| reciter_dir = Path("banna") |
| surah_str = "001" |
| surah_path = reciter_dir / surah_str |
| |
| all_opus = sorted(list(surah_path.glob(f"{surah_str}*.opus"))) |
| verse_opus_files = [f for f in all_opus if len(f.stem) > 3] |
| |
| concat_txt_path = surah_path / f"concat_{surah_str}.txt" |
| target_opus = surah_path / f"{surah_str}_test.opus" |
| |
| cumulative_offset = 0 |
| with open(concat_txt_path, 'w') as f_out: |
| for opus_f in verse_opus_files: |
| f_out.write(f"file '{opus_f.name}'\n") |
| dur = get_ogg_opus_duration(opus_f) |
| cumulative_offset += dur |
| print(f"{opus_f.name} dur: {dur} ms") |
| |
| print(f"Total cumulative: {cumulative_offset} ms") |
| |
| subprocess.run([ |
| "ffmpeg", "-y", "-hide_banner", "-loglevel", "error", |
| "-f", "concat", "-safe", "0", |
| "-i", str(concat_txt_path), |
| "-c", "copy", |
| str(target_opus) |
| ], check=True) |
| |
| combined_dur = get_ogg_opus_duration(target_opus) |
| print(f"Combined opus duration: {combined_dur} ms") |
| |
| if __name__ == '__main__': |
| test_concat() |
|
|