Skip to content

Instantly share code, notes, and snippets.

@antlauzon
Created December 10, 2018 15:21
Show Gist options
  • Save antlauzon/765909ee36206ee73721eb3c46838853 to your computer and use it in GitHub Desktop.
Save antlauzon/765909ee36206ee73721eb3c46838853 to your computer and use it in GitHub Desktop.
ASCII Waveform Generator
import argparse
import subprocess
import sys
import tempfile
def generate_view(infile, wave_width, wave_height):
_, datfilename = tempfile.mkstemp(suffix='.dat')
datfile = open(datfilename, 'r')
p = subprocess.Popen(['sox', infile, datfilename],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
amplitudes = [abs(float(v.split()[1])) for v in datfile.readlines()[2:]]
num_ivals = len(amplitudes) / wave_width
ival_len = len(amplitudes) % wave_width
avg_amplitudes = []
for i in range(wave_width):
start_ival = int(i * num_ivals + min(i, ival_len))
end_ival = int((i + 1) * num_ivals + min(i + 1, ival_len))
ival = amplitudes[start_ival:end_ival]
avg_amplitudes.append(sum(ival)/len(ival))
upper_rows = []
wave_marker = {True: '|'}
for y in reversed(range(wave_height)):
row = []
for amp in avg_amplitudes:
row.append(wave_marker.get(amp > y * (.5/wave_height), ' '))
upper_rows.append(row)
lower_rows = [r for r in reversed(upper_rows[:-1])]
ascii_waveform = ''
for row in upper_rows + lower_rows:
row_output = ''.join(row)
ascii_waveform += ''.join(row) + '\n'
return ascii_waveform
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--infile', help='a sound file')
parser.add_argument('-y', '--width', type=int, default=80,
help='the width of the desired waveform output in characters')
parser.add_argument('-x', '--height', type=int, default=20,
help='the height of the desired waveform in characters')
args = parser.parse_args()
print(generate_view(args.infile, args.width, args.height))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment