Slice audio in chunks
Browse files- slice_audio.py +64 -0
slice_audio.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import argparse
|
3 |
+
|
4 |
+
START = 00
|
5 |
+
SECONDS = 150
|
6 |
+
FOLDER = "chunks"
|
7 |
+
|
8 |
+
def seconds_to_hms(seconds):
|
9 |
+
hour = 00
|
10 |
+
minute = 00
|
11 |
+
second = seconds
|
12 |
+
|
13 |
+
while second >= 60:
|
14 |
+
minute += 1
|
15 |
+
second -= 60
|
16 |
+
while minute >= 60:
|
17 |
+
hour += 1
|
18 |
+
minute -= 60
|
19 |
+
|
20 |
+
return hour, minute, second
|
21 |
+
|
22 |
+
def hms_to_seconds(hour, minute, second):
|
23 |
+
return hour*3600 + minute*60 + second
|
24 |
+
|
25 |
+
def main(args):
|
26 |
+
input = args.input
|
27 |
+
# name, extension = input.split(".")
|
28 |
+
path, filename = os.path.split(input)
|
29 |
+
name, extension = os.path.splitext(filename)
|
30 |
+
print(path, name, extension)
|
31 |
+
|
32 |
+
# Get audio duration in seconds
|
33 |
+
duration = float(os.popen(f'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {input}').read())
|
34 |
+
hour, minute, second = seconds_to_hms(int(duration))
|
35 |
+
print(f"Audio duration = {duration} = {hour}:{minute:02d}:{second}")
|
36 |
+
|
37 |
+
# Number of chunks
|
38 |
+
num_chunks = -(-int(duration) // SECONDS) # Redondeo hacia arriba
|
39 |
+
|
40 |
+
# Slice audio into SECONDS chunks
|
41 |
+
hour, minute, second = seconds_to_hms(SECONDS) # Duration of each chunk
|
42 |
+
for chunk in range(num_chunks):
|
43 |
+
start_time = chunk * SECONDS
|
44 |
+
hour_start, minute_start, second_start = seconds_to_hms(start_time) # Start time of each chunk
|
45 |
+
|
46 |
+
if start_time + SECONDS > duration:
|
47 |
+
hour, minute, second = seconds_to_hms(duration - start_time)
|
48 |
+
else:
|
49 |
+
hour, minute, second = seconds_to_hms(SECONDS)
|
50 |
+
|
51 |
+
output = f"{FOLDER}/{name}_chunk{chunk:003d}{extension}"
|
52 |
+
|
53 |
+
if start_time + SECONDS > duration:
|
54 |
+
command = f'ffmpeg -i {input} -ss {hour_start:02d}:{minute_start:02d}:{second_start:02d} {output}'
|
55 |
+
else:
|
56 |
+
command = f'ffmpeg -i {input} -ss {hour_start:02d}:{minute_start:02d}:{second_start:02d} -t {hour:02}:{minute:02}:{second:02} {output}'
|
57 |
+
print(command)
|
58 |
+
os.system(command)
|
59 |
+
|
60 |
+
if __name__ == "__main__":
|
61 |
+
argparser = argparse.ArgumentParser(description='Slice audio into smaller chunks')
|
62 |
+
argparser.add_argument('input', help='Input audio file')
|
63 |
+
args = argparser.parse_args()
|
64 |
+
main(args)
|