首页 > 解决方案 > 如何更改图像大小以允许更长的音频(wav 到 png)

问题描述

想知道是否有人可以帮助我做一些简单的事情。我正在运行一个将 WAV 文件转换为 PNG 的脚本,我遇到的问题是我无法加载超过 1 秒的 WAV 文件。

我需要更改 imageSize = math.sqrt(44100) 以增加允许的图像大小,但我不确定如何去做。我想加载一个 60 秒的 WAV 文件。

我试过 math.sqrt(44100*60) 但我仍然得到一个 55KB 的输出 PNG。(60秒的音频文件为5MB)代码:

from PIL import Image
import wave, struct, sys, math

##
# Collect input
##
if sys.argv[1][-4:] != '.wav':
    sys.exit("First argument should be a .wav file")

if sys.argv[2][-4:] != '.png':
    sys.exit("Second argument should be a .png file")

##
# Conversion:
##

# Wave file needs to be 16 bit mono
waveFile = wave.open(sys.argv[1], 'r')

if waveFile.getnchannels() != 1:
    sys.exit("ERROR: The wave file should be single channel (mono)")

if waveFile.getframerate() != 44100:
    sys.exit("ERROR: The samplerate should be 44,100")

imageRgbArray = list()

waveLength = waveFile.getnframes()

# Create the image size (based on the length)
imageSize = math.sqrt(44100)

# Loop through the wave file
for i in range(0, 44100):

    # Try to read frame, if not possible fill with 0x0
    try:
        waveData = waveFile.readframes(1)
        data = struct.unpack("<h", waveData) # This loads the wave bit
        convertedData = int(data[0]) + 32768 # This adds 16bit/2 (=32768) to the data
    except:
        convertedData = 0
        pass

    # This converts the number into a hex value.
    convertedDataHex = hex(convertedData)

    # convert the value to a string and strips first two characters
    hexString = str(convertedDataHex)[2:]

    # Check how much the string should be prefixed to get the color hex length (= 6 char)
    count = 6 - len(hexString)

    # Prefix with a zero
    while (count > 0):
        hexString = "0" + hexString
        count -= 1

    # Convert into RGB value
    rgbData = tuple(int(hexString[i:i + 6 // 3], 16) for i in range(0, 6, 6 // 3)) # Convert to RGB data

    # Add the RGB value to the image array
    imageRgbArray.append(rgbData)

# Create new image
im = Image.new('RGB', (int(imageSize), int(imageSize)))

# Add image data
im.putdata(imageRgbArray)

# Save image
im.save(sys.argv[2])

完整的项目(不是我的): https ://github.com/bobvanluijt/audio-convolutional-neural-network

标签: python

解决方案


我通过更改这几行来让它工作,sqrt 的问题是它给出了浮点数并且向下舍入,所以图像没有足够的像素,我们可以通过使用天花板函数来防止这种情况。

...
waveLength = waveFile.getnframes()

# Create the image size (based on the length)
imageSize = math.ceil(math.sqrt(waveLength))

# Loop through the wave file
for i in range(waveLength):
    ...

这种方法的一个好处是我们不再受限于给定比特率的样本,因此您可以删除。

if waveFile.getframerate() != 44100:
    sys.exit("ERROR: The samplerate should be 44,100")

推荐阅读