Skip to content

Instantly share code, notes, and snippets.

@xyb
Last active February 17, 2023 03:23
Show Gist options
  • Save xyb/acb56a1033a4ee395efb5f2daadc8230 to your computer and use it in GitHub Desktop.
Save xyb/acb56a1033a4ee395efb5f2daadc8230 to your computer and use it in GitHub Desktop.
get audio volumes samples, assited by ChatGPT
from pydub import AudioSegment
import numpy as np
def get_volumes(audio_path, format, chunks_number=100):
audio = AudioSegment.from_file(audio_path, format=format)
segment_length = len(audio) // chunks_number
volumes = []
for i in range(chunks_number):
start_time = i * segment_length
end_time = (i + 1) * segment_length
segment = audio[start_time:end_time]
samples = np.array(segment.get_array_of_samples())
volume = np.abs(samples).mean()
volumes.append(volume)
# Set the maximum mean as 100
max_mean = max(volumes)
part_means = [int(100 * mean / max_mean) for mean in volumes]
return part_means
if __name__ == '__main__':
print(' '.join([str(i) for i in get_volumes("file.mp3", "mp3", 100)]))
@xyb
Copy link
Author

xyb commented Feb 17, 2023

usage:

❯ python volumes100.py 
6 11 11 10 12 13 22 18 15 10 12 10 14 25 25 16 10 13 10 14 14 25 15 10 13 10 16 19 61 63 39 62 91 39 61 82 60 34 62 90 36 82 82 65 51 63 96 60 57 62 83 46 42 97 72 56 91 71 51 42 85 74 55 72 67 51 36 79 83 45 88 73 69 46 71 100 57 57 83 64 42 71 97 45 90 60 56 32 31 49 27 57 36 54 34 32 46 30 54 38
❯ pip install sparklines
❯ python volumes100.py | sparklines
▁▁▁▁▁▂▂▂▂▁▁▁▂▂▂▂▁▂▁▂▂▂▂▁▂▁▂▂▅▅▃▅▇▃▅▇▅▃▅▇▃▇▇▅▄▅█▅▅▅▇▄▄█▆▅▇▆▄▄▇▆▅▆▆▄▃▆▇▄▇▆▆▄▆█▅▅▇▅▄▆█▄▇▅▅▃▃▄▃▅▃▅▃▃▄▃▅▃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment