所以我用PyAudio录制了一些音频,我想要可视化,目前我正在将奥迪框架保存到一个文件中,然后再次使用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
发布于 2021-02-27 05:23:25
frames是字节串的列表。每个元素只是一个2048字节的块。您需要它是一个16位元素的列表。你可以用'array`‘做到这一点。
import array
pcm = array.array('h')
pcm.frombytes( b''.join(frames))
ax.plot(pcm)
``https://stackoverflow.com/questions/66392783
复制相似问题