解码 PyAudio 记录

Decode PyAudio Record

所以我用 PyAudio 录制了一些音频,我想将其可视化,目前我正在将 audi-frames 保存到一个文件中,然后再次用 tensorflow 加载它:

def loadAudioFromFile(file):
    return decodeAudio(tf.io.read_file(file))


def decodeAudio(binary):
    foo, _ = tf.audio.decode_wav(binary, desired_channels=1)
    return tf.squeeze(foo, axis=-1)

录音与保存:

RATE = 44100
RECORD_SECONDS = 1
CHUNK = 1024
CHANNELS = 1
p = pyaudio.PyAudio()

stream = p.open(format=pyaudio.paInt16,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                frames_per_buffer=CHUNK)

print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)


print("* done recording")
# stop stream (4)
stream.stop_stream()
stream.close()

# close PyAudio (5)
p.terminate()
# save to file
file = wave.open("test.wav", 'wb')

file.setnchannels(1)
file.setsampwidth(p.get_sample_size(pyaudio.paInt16))
file.setframerate(RATE)

# Write and Close the File
file.writeframes(b''.join(frames))
file.close()

以及加载和绘图:

fig, axes = plt.subplots(1, 1, figsize=(10, 10))
ax = axes
audio = loadAudioFromFile("test.wav")
ax.plot(audio)
ax.set_yticks(np.arange(-1.2, 1.2, 0.2))
ax.set_title("audio")

但本来我想直接加载记录的数据,而不必先将其保存到硬盘。但是当我这样做时:

ax.plot(b''.join(frames))

它不起作用,因为解码问题(我认为是因为 16 位与 8 位)。 在 C++ 或类似语言中,这对我来说通常不是问题,但我是 python 的新手,有点迷路了 :'D

frames 是一个字节串列表。每个元素只是一个 2048 字节的块。您需要它是 16 位元素的列表。您可以使用“array”来做到这一点。

import array

pcm = array.array('h')
pcm.frombytes( b''.join(frames))
ax.plot(pcm)
``