python - 如何增加来自 python 中 pyaudio 的字节数组的体积
问题描述
我正在将音频从麦克风流式传输到我的扬声器。但我想增加现场声音的音量,但我想不出办法,我已经在谷歌搜索了一段时间。
她是我的密码
import pyaudio
Chunk = 1024
AudioFormat = pyaudio.paInt16
Channels = 2
Rate = 44100
PortAudio = pyaudio.PyAudio()
sourceDevice = PortAudio.open(format=AudioFormat,
channels=Channels,
rate=Rate,
input=True,
input_device_index=2,
frames_per_buffer=Chunk
)
destinationDevice = PortAudio.open(format=AudioFormat,
channels=Channels,
rate=Rate,
output=True,
output_device_index=4,
frames_per_buffer=Chunk
)
while True:
try:
data = sourceDevice.read(Chunk)
except OSError:
data = '\x00' * Chunk
except IOError as ex:
if ex[1] != pyaudio.paInputOverflowed:
raise
data = '\x00' * Chunk
# Doing Something To Data Here To Incrase Volume Of It
data = data # Function Here??
destinationDevice.write(data, Chunk, exception_on_underflow=True)
数据变量是什么的一个例子(这被缩短了很多,原来是MASSIVE)b'\xec\x00G\x01\xa7\x01\xbe\x01\x95\x00\xf7\x00+\x00\x91 \x00\xa1\x01W\x01\xec\x01\x94\x01n\x00\xac\x00I\x00\xa4\x00\xfb\x00"\x01g\x00\x8d\x00*\x00m\x00\xde\x00 \x04\x01\xb2\x00\xc7\x005\x00-\x00(\x01\xb0\x00\xec\x01Q\x01.'
解决方案
您可以使用 numpy 将原始数据转换为 numpy 数组,然后将数组乘以体积比并将其写入输出流。
from math import sqrt
import numpy as np
# ...
# convert the linear volume to a logarithmic scale (see explanation below)
volumeFactor = 2
multiplier = pow(2, (sqrt(sqrt(sqrt(volumeFactor))) * 192 - 192)/6)
while True:
try:
data = sourceDevice.read(Chunk)
except OSError:
data = '\x00' * Chunk
except IOError as ex:
if ex[1] != pyaudio.paInputOverflowed:
raise
data = '\x00' * Chunk
# Doing Something To Data Here To Incrase Volume Of It
numpy_data = np.fromstring(data, dtype=np.int16)
# double the volume using the factor computed above
np.multiply(numpyData, volumeMultiplier,
out=numpyData, casting="unsafe")
destinationDevice.write(numpy_data.tostring(), Chunk, exception_on_underflow=True)
这个概念是音频数据在概念上是一个样本数组,每个样本都有一个取决于位“深度”的值。标准数字音频(如 CD 音频)为 44100kHz,16 位立体声,这意味着每秒钟有 88200 个样本(因为它是立体声),每个样本占用 2 个字节(8 位 + 8 位)。如果你同样改变每个样本的值,你实际上会改变它的音量。
现在,问题是感知音量不是线性的,而是对数的。所以,如果你想获得两倍的音量,你不能只是双倍的样本值。
我正在使用几年前发现的转换(如果我没记错的话,来自 Ardor 滑块),它应该足够准确。
但是要小心,您很容易获得非常高的电平,这会导致声音失真。
推荐阅读
- c++ - 巴比伦平方根算法输出不匹配示例
- visual-studio-code - 如何将 Visual Studio 代码输出路径颜色从白色更改为绿色。我被卡住了,有人请帮我设置一下吗?
- python - 有没有办法在按下按钮时先打开红色 LED,然后打开蓝色 LED,最后打开绿色 LED?
- java - 如何使用 Spring 将运行时创建的字符串注入另一个类
- javascript - 使用 Redux Toolkit 在切片之间共享操作
- javascript - 使用新文档 ID 更新 mongodb 文档
- html - 如何防止我网站中的视频在 ipad 上以 PIP 模式播放?
- c++ - 是否可以 dllexport 已通过 using-declaration 访问的方法?
- java - 如何验证是否显示 toast 消息?
- mongodb - Mongodb聚合数组分区和计数