如何使用 .txt 文件中的二进制输入绘制 PCM 波

How to plot a PCM wave using the binary inputs from a .txt file

在我的例子中,我将有一个 PCM.txt 文件,其中包含如下所示的 PCM 数据的二进制表示形式。

[1. 1. 0. 1. 0. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1. 0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1. 0. 1. 0. 1. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 0. 1.]

1的意思是二进制1

0的意思是二进制0

这不过是 100 个数据样本。

  1. 是否可以实现一个 python 代码,它将此 PCM.txt 作为输入读取并使用 matplotlib 绘制此 PCM 数据。 ?你能给我一些实现这个场景的技巧吗?
  2. 这个绘制的图形看起来像方波吗?

我想你想要这个:

import matplotlib.pyplot as plt 
import numpy as np

x = np.arange(100)
y = [1.,1.,0.,1.,0.,1.,1.,1.,1.,1.,0.,1.,1.,1.,1.,1.,1.,1.,0.,1.,1.,1.,0.,1.,0.,1.,0.,1.,0.,0.,1.,0.,0.,0.,0.,0.,1.,0.,0.,0.,0.,0,0.,0.,1.,0.,0.,1.,0.,1.,0.,1.,0.,1.,0.,1.,1.,1.,1.,1.,0.,1.,1.,1.,1.,1.,1.,1.,0.,1.,1.,1.,0.,1.,0.,1.,0.,1.,0.,0.,1.,0.,0.,0.,0.,0.,1.,0.,0.,0.,0.,0.,0.,0.,1.,0.,0.,1.,0.,1.]

plt.step(x, y)
plt.show() 

如果您在阅读文件时遇到问题,您可以使用正则表达式来查找看起来像数字的内容:

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

# Slurp entire file
with open('data') as f:
    s = f.read()

# Set y to anything that looks like a number
y = re.findall(r'[0-9.]+', s)

# Set x according to number of samples found
x = np.arange(len(y))

# Plot that thing
plt.step(x, y)
plt.show() 

关键词: Python, PCM, PCM signal, plot, Matplotlib, regex.