summaryrefslogtreecommitdiff
path: root/animism-align/cli/commands/peaks/parse.py
blob: dc9a0a210fb4fb1a4ece7bf81793794d62fbaa55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
Extract peaks from an MP3 file.
"""

import click

from app.site.builder import build_site, build_file

@click.command()
@click.option('-i', '--input', 'fp_in', required=False,
  help='Input file')
@click.pass_context
def cli(ctx, fp_in):
  """Extract peaks from an MP3 file.
  """
  import os
  import math
  import librosa
  import numpy
  import json

  from app.settings import app_cfg

  print(f"Loading {fp_in}")
  y, sr = librosa.load(fp_in, sr=None)

  sr_10 = math.floor(sr / 10)
  steps = math.floor(y.shape[0] / sr_10)

  peaks = numpy.ndarray(steps * 2)

  for i in range(steps):
    offset = i * sr_10
    slice = y[offset:offset + sr_10]
    peaks[i * 2] = float('%.3f' % slice.min())
    peaks[i * 2 + 1] = float('%.3f' % slice.max())

  with open(os.path.join(app_cfg.DIR_DATA_STORE, 'peaks.json'), 'w') as fp_out:
    json.dump(peaks.tolist(), fp_out, separators=(',', ':'))