58

我刚刚用 scipy 读取了一个 wav 文件,现在我想使用 matplotlib 制作文件的绘图,在“y 比例”上我想查看幅度,在“x 比例”上我想查看帧数!任何帮助我该怎么做?谢谢!

from scipy.io.wavfile import read
import numpy as np
from numpy import*
import matplotlib.pyplot as plt
a=read("C:/Users/Martinez/Desktop/impulso.wav")
print a
4

8 回答 8

84

您可以调用 wave lib 来读取音频文件。

要绘制波形,请使用 matplotlib 中的“plot”函数

import matplotlib.pyplot as plt
import numpy as np
import wave
import sys


spf = wave.open("wavfile.wav", "r")

# Extract Raw Audio from Wav File
signal = spf.readframes(-1)
signal = np.fromstring(signal, "Int16")


# If Stereo
if spf.getnchannels() == 2:
    print("Just mono files")
    sys.exit(0)

plt.figure(1)
plt.title("Signal Wave...")
plt.plot(signal)
plt.show()

你会有类似的东西:在此处输入图像描述

要以秒为单位绘制 x 轴,您需要获取帧速率并除以信号的大小,您可以使用 numpy 的 linspace 函数创建一个与音频文件大小呈线性间隔的时间向量,最后您可以再次使用 plot喜欢plt.plot(Time,signal)

import matplotlib.pyplot as plt
import numpy as np
import wave
import sys


spf = wave.open("Animal_cut.wav", "r")

# Extract Raw Audio from Wav File
signal = spf.readframes(-1)
signal = np.fromstring(signal, "Int16")
fs = spf.getframerate()

# If Stereo
if spf.getnchannels() == 2:
    print("Just mono files")
    sys.exit(0)


Time = np.linspace(0, len(signal) / fs, num=len(signal))

plt.figure(1)
plt.title("Signal Wave...")
plt.plot(Time, signal)
plt.show()

以秒为单位的新绘图 x 轴:

在此处输入图像描述

于 2013-09-04T23:15:47.847 回答
28

或者,如果您想使用 SciPy,您还可以执行以下操作:

from scipy.io.wavfile import read
import matplotlib.pyplot as plt

# read audio samples
input_data = read("Sample.wav")
audio = input_data[1]
# plot the first 1024 samples
plt.plot(audio[0:1024])
# label the axes
plt.ylabel("Amplitude")
plt.xlabel("Time")
# set the title  
plt.title("Sample Wav")
# display the plot
plt.show()
于 2014-08-02T14:16:03.680 回答
16

根据@ederwander 的回答,这是一个也可以处理立体声输入的版本

import matplotlib.pyplot as plt
import numpy as np
import wave

file = 'test.wav'

with wave.open(file,'r') as wav_file:
    #Extract Raw Audio from Wav File
    signal = wav_file.readframes(-1)
    signal = np.fromstring(signal, 'Int16')

    #Split the data into channels 
    channels = [[] for channel in range(wav_file.getnchannels())]
    for index, datum in enumerate(signal):
        channels[index%len(channels)].append(datum)

    #Get time from indices
    fs = wav_file.getframerate()
    Time=np.linspace(0, len(signal)/len(channels)/fs, num=len(signal)/len(channels))

    #Plot
    plt.figure(1)
    plt.title('Signal Wave...')
    for channel in channels:
        plt.plot(Time,channel)
    plt.show()

在此处输入图像描述

于 2017-02-20T19:31:32.507 回答
13

这是绘制波形文件的波形和频谱的代码

import wave
import numpy as np
import matplotlib.pyplot as plt

signal_wave = wave.open('voice.wav', 'r')
sample_rate = 16000
sig = np.frombuffer(signal_wave.readframes(sample_rate), dtype=np.int16)

对于波形文件的整个片段

sig = sig[:]

对于波形文件的部分片段

sig = sig[25000:32000]

分离立体声通道

left, right = data[0::2], data[1::2]

绘制波形 (plot_a) 和频谱 (plot_b)

plt.figure(1)

plot_a = plt.subplot(211)
plot_a.plot(sig)
plot_a.set_xlabel('sample rate * time')
plot_a.set_ylabel('energy')

plot_b = plt.subplot(212)
plot_b.specgram(sig, NFFT=1024, Fs=sample_rate, noverlap=900)
plot_b.set_xlabel('Time')
plot_b.set_ylabel('Frequency')

plt.show()

波信号和信号的频谱图

于 2019-08-08T07:45:41.983 回答
12

只是一个观察(我不能添加评论)。

您将收到以下消息:

DeprecationWarning:不推荐使用数字样式的类型代码,将来会导致错误。

不要将 np.fromstring 与二进制文件一起使用。而不是 signal = np.fromstring(signal, 'Int16'),最好使用 signal = np.frombuffer(signal, dtype='int16')

于 2018-02-25T21:11:59.323 回答
4

这是处理单声道/立体声和 8 位/16 位 PCM 的版本。

import matplotlib.pyplot as plt
import numpy as np
import wave

file = 'test.wav'

wav_file = wave.open(file,'r')

#Extract Raw Audio from Wav File
signal = wav_file.readframes(-1)
if wav_file.getsampwidth() == 1:
    signal = np.array(np.frombuffer(signal, dtype='UInt8')-128, dtype='Int8')
elif wav_file.getsampwidth() == 2:
    signal = np.frombuffer(signal, dtype='Int16')
else:
    raise RuntimeError("Unsupported sample width")

# http://schlameel.com/2017/06/09/interleaving-and-de-interleaving-data-with-python/
deinterleaved = [signal[idx::wav_file.getnchannels()] for idx in range(wav_file.getnchannels())]

#Get time from indices
fs = wav_file.getframerate()
Time=np.linspace(0, len(signal)/wav_file.getnchannels()/fs, num=len(signal)/wav_file.getnchannels())

#Plot
plt.figure(1)
plt.title('Signal Wave...')
for channel in deinterleaved:
    plt.plot(Time,channel)
plt.show()
于 2018-08-18T09:18:18.080 回答
1

我想我可以把它放在评论中,但是基于@ederwander 和@TimSC 的答案,我想做一些更精细(如详细)和美观的东西。下面的代码创建了我认为非常好的立体声或单声道波形文件(我不需要标题,所以我只是将其注释掉,也不需要 show 方法 - 只需要保存图像文件) .

这是一个渲染的立体 wav 示例: 在此处输入图像描述

和代码,与我提到的差异:

import matplotlib.pyplot as plt
import numpy as np
import wave

file = '/Path/to/my/audio/file/DeadMenTellNoTales.wav'

wav_file = wave.open(file,'r')

#Extract Raw Audio from Wav File
signal = wav_file.readframes(-1)
if wav_file.getsampwidth() == 1:
    signal = np.array(np.frombuffer(signal, dtype='UInt8')-128, dtype='Int8')
elif wav_file.getsampwidth() == 2:
    signal = np.frombuffer(signal, dtype='Int16')
else:
    raise RuntimeError("Unsupported sample width")

# http://schlameel.com/2017/06/09/interleaving-and-de-interleaving-data-with-python/
deinterleaved = [signal[idx::wav_file.getnchannels()] for idx in range(wav_file.getnchannels())]

#Get time from indices
fs = wav_file.getframerate()
Time=np.linspace(0, len(signal)/wav_file.getnchannels()/fs, num=len(signal)/wav_file.getnchannels())
plt.figure(figsize=(50,3))
#Plot
plt.figure(1)
#don't care for title
#plt.title('Signal Wave...')
for channel in deinterleaved:
    plt.plot(Time,channel, linewidth=.125)
#don't need to show, just save
#plt.show()
plt.savefig('/testing_folder/deadmentellnotales2d.png', dpi=72)
于 2019-08-09T23:54:01.603 回答
0

我想出了一个更灵活、更高效的解决方案:

  • 下采样用于实现每秒两个样本。这是通过计算每个窗口的绝对值的平均值来实现的。结果看起来像来自 SoundCloud 等流媒体网站的波形。
  • 支持多通道(感谢@Alter)
  • Numpy 用于每个操作,这比遍历数组的性能要高得多。
  • 该文件分批处理以支持非常大的文件。
import matplotlib.pyplot as plt
import numpy as np
import wave
import math

file = 'audiofile.wav'

with wave.open(file,'r') as wav_file:
    num_channels = wav_file.getnchannels()
    frame_rate = wav_file.getframerate()
    downsample = math.ceil(frame_rate * num_channels / 2) # Get two samples per second!

    process_chunk_size = 600000 - (600000 % frame_rate)

    signal = None
    waveform = np.array([])

    while signal is None or signal.size > 0:
        signal = np.frombuffer(wav_file.readframes(process_chunk_size), dtype='int16')

        # Take mean of absolute values per 0.5 seconds
        sub_waveform = np.nanmean(
            np.pad(np.absolute(signal), (0, ((downsample - (signal.size % downsample)) % downsample)), mode='constant', constant_values=np.NaN).reshape(-1, downsample),
            axis=1
        )

        waveform = np.concatenate((waveform, sub_waveform))

    #Plot
    plt.figure(1)
    plt.title('Waveform')
    plt.plot(waveform)
    plt.show()
于 2019-11-18T16:01:46.813 回答