Skip to content

Instantly share code, notes, and snippets.

@PC-CNT
Created June 21, 2024 16:06
Show Gist options
  • Select an option

  • Save PC-CNT/85fa79570bded439813063841d98c6b5 to your computer and use it in GitHub Desktop.

Select an option

Save PC-CNT/85fa79570bded439813063841d98c6b5 to your computer and use it in GitHub Desktop.
waveにsmplつけるやつ
import os
import struct
import sys
import wave
def set_loop(input_path, output_path, start_time=None, end_time=None):
with open(input_path, 'rb') as f:
wave_data = f.read()
sample_rate = None
for i in range(len(wave_data) - 4):
if wave_data[i:i+4] == b'fmt ':
sample_rate = struct.unpack('<I', wave_data[i+12:i+16])[0]
break
if sample_rate is None:
return
with wave.open(input_path, 'rb') as wav_file:
total_frames = wav_file.getnframes()
if start_time is None:
start_time = 0.0
if end_time is None:
end_time = total_frames / sample_rate
start = int(sample_rate * start_time)
end = int(sample_rate * end_time)
smpl_index = None
for i in range(len(wave_data) - 4):
if wave_data[i:i+4] == b'smpl':
smpl_index = i
smpl_chunk_size = struct.unpack('<I', wave_data[i+4:i+8])[0] + 8
wave_data = wave_data[:i] + wave_data[i + smpl_chunk_size:]
break
smpl_chunk = bytearray(68)
smpl_chunk[0:4] = b'smpl'
struct.pack_into('<I', smpl_chunk, 4, 60)
struct.pack_into('<I', smpl_chunk, 20, 60)
struct.pack_into('<I', smpl_chunk, 36, 1)
struct.pack_into('<I', smpl_chunk, 52, start)
struct.pack_into('<I', smpl_chunk, 56, end)
wave_data += smpl_chunk
riff_index = wave_data.find(b'RIFF')
if riff_index == -1:
return
file_size = len(wave_data) - 8
wave_data = wave_data[:riff_index + 4] + \
struct.pack('<I', file_size) + wave_data[riff_index + 8:]
with open(output_path, 'wb') as f:
f.write(wave_data)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: python script.py <input_path> [start_time] [end_time]")
sys.exit(1)
input_path = sys.argv[1]
output_path = f"{os.path.splitext(input_path)[0]}_smpl.wav"
start_time = float(sys.argv[2]) if len(sys.argv) > 2 else None
end_time = float(sys.argv[3]) if len(sys.argv) > 3 else None
set_loop(input_path, output_path, start_time, end_time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment