为任意音频文件生成缩略图

时间:2012-02-08 19:41:02

标签: python audio visualization

我想在最大尺寸为180×180像素的图像中表示音频文件。

我想生成这个图像,以便它以某种方式给出音频文件的表示,把它想象成SoundCloud的波形(振幅图)?。

Screenshot of Soundcloud's player

我想知道你们中是否有人为此事做点什么。我一直在寻找一下,主要是“音频可视化”和“音频缩略图”,但我没有找到任何有用的东西。

我首先posted this to ux.stackexchange.com,这是我试图联系任何致力于此的程序员。

3 个答案:

答案 0 :(得分:3)

您还可以将音频分解成块并测量RMS(响度的度量)。假设你想要一个180像素宽的图像。

我将使用pydub,这是我在std lib wave模式下编写的轻量级包装器:

from pydub import AudioSegment

# first I'll open the audio file
sound = AudioSegment.from_mp3("some_song.mp3")

# break the sound 180 even chunks (or however
# many pixels wide the image should be)
chunk_length = len(sound) / 180

loudness_of_chunks = []
for i in range(180):
    start = i * chunk_length
    end = chunk_start + chunk_length

    chunk = sound[start:end]
    loudness_of_chunks.append(chunk.rms)

for循环可以表示为以下列表理解,我只是希望它清楚:

loudness_of_chunks = [
    sound[ i*chunk_length : (i+1)*chunk_length ].rms
    for i in range(180)]

现在唯一的想法是将RMS缩小到0 - 180比例(因为你希望图像高180像素)

max_rms = max(loudness_of_chunks)

scaled_loudness = [ (loudness / max_rms) * 180 for loudness in loudness_of_chunks]

我会给你留下实际像素的图,我对PIL或ImageMagik不是很有经验:/

答案 1 :(得分:2)

请查看有关wav2png.py

的博客文章

答案 2 :(得分:1)

根据Jiaaro的回答(感谢写pydub!),并为web2py构建了我的两分钱:

def generate_waveform():
    img_width = 1170
    img_height = 140
    line_color = 180
    filename = os.path.join(request.folder,'static','sounds','adg3.mp3')


    # first I'll open the audio file
    sound = pydub.AudioSegment.from_mp3(filename)

    # break the sound 180 even chunks (or however
    # many pixels wide the image should be)
    chunk_length = len(sound) / img_width

    loudness_of_chunks = [
        sound[ i*chunk_length : (i+1)*chunk_length ].rms
        for i in range(img_width)
    ]
    max_rms = float(max(loudness_of_chunks))
    scaled_loudness = [ round(loudness * img_height/ max_rms)  for loudness in loudness_of_chunks]

    # now convert the scaled_loudness to an image
    im = Image.new('L',(img_width, img_height),color=255)
    draw = ImageDraw.Draw(im)
    for x,rms in enumerate(scaled_loudness):
        y0 = img_height - rms
        y1 = img_height
        draw.line((x,y0,x,y1), fill=line_color, width=1)
    buffer = cStringIO.StringIO()
    del draw
    im = im.filter(ImageFilter.SMOOTH).filter(ImageFilter.DETAIL)
    im.save(buffer,'PNG')
    buffer.seek(0)
    return response.stream(buffer, filename=filename+'.png')