Skip to content

Instantly share code, notes, and snippets.

@moeseth
Created October 12, 2015 08:19
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save moeseth/130cd92dc47c56c47030 to your computer and use it in GitHub Desktop.
Save moeseth/130cd92dc47c56c47030 to your computer and use it in GitHub Desktop.
Create Soundcloud style waveform from Audio in Python
from pydub import AudioSegment
from matplotlib import pyplot as plot
from PIL import Image, ImageDraw
import numpy as np
import os
src = "./test.mp3"
audio = AudioSegment.from_file(src)
data = np.fromstring(audio._data, np.int16)
fs = audio.frame_rate
BARS = 100
BAR_HEIGHT = 60
LINE_WIDTH = 5
length = len(data)
RATIO = length/BARS
count = 0
maximum_item = 0
max_array = []
highest_line = 0
for d in data:
if count < RATIO:
count = count + 1
if abs(d) > maximum_item:
maximum_item = abs(d)
else:
max_array.append(maximum_item)
if maximum_item > highest_line:
highest_line = maximum_item
maximum_item = 0
count = 1
line_ratio = highest_line/BAR_HEIGHT
im = Image.new('RGBA', (BARS * LINE_WIDTH, BAR_HEIGHT), (255, 255, 255, 1))
draw = ImageDraw.Draw(im)
current_x = 1
for item in max_array:
item_height = item/line_ratio
current_y = (BAR_HEIGHT - item_height)/2
draw.line((current_x, current_y, current_x, current_y + item_height), fill=(169, 171, 172), width=4)
current_x = current_x + LINE_WIDTH
im.show()
@moeseth
Copy link
Author

moeseth commented Oct 12, 2015

enter image description here

@StanSilas
Copy link

Hi! Thanks for the this!
I'm interested in making this output interactive. Something like this but interactive which displays audio level at the point of hovering.
TBH I want to replicate soundcloud waveform.
Please advise

@bowbowbow
Copy link

bowbowbow commented Aug 9, 2018

Awesome!

@reiven
Copy link

reiven commented May 9, 2020

simply amazing, thanks!!

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