torchaudio - Python wave 读取音频数据对比

2023-11-21 10:50

本文主要是介绍torchaudio - Python wave 读取音频数据对比,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

torchaudio - Python wave 读取音频数据对比

1. torchaudio: an audio library for PyTorch

https://github.com/pytorch/audio

Data manipulation and transformation for audio signal processing, powered by PyTorch.

torchaudio: an audio library for PyTorch
https://github.com/pytorch/audio

The following is the corresponding torchaudio versions and supported Python versions.

torchtorchaudiopython
master / nightlymaster / nightly>=3.6
1.5.00.5.0>=3.5
1.4.00.4.0==2.7, >=3.5, <=3.8

2. torchaudio.load(filepath, out=None, normalization=True, channels_first=True, num_frames=0, offset=0, signalinfo=None, encodinginfo=None, filetype=None)

https://pytorch.org/audio/

Loads an audio file from disk into a tensor.
将音频文件从磁盘加载到张量中。

2.1 Parameters

filepath (str or pathlib.Path) – Path to audio file. - 音频文件的路径。

out (torch.Tensor, optional) – An output tensor to use instead of creating one. (Default: None) - 使用输出张量 out 而不是创建一个张量。

normalization (bool, number, or callable, optional) – If boolean True, then output is divided by 1 << 31 (assumes signed 32-bit audio), and normalizes to [-1, 1]. If number, then output is divided by that number. If callable, then the output is passed as a parameter to the given function, then the output is divided by the result. (Default: True)

channels_first (bool) – Set channels first or length first in result. (Default: True) - 返回结果中第一维度是 channels or length。

num_frames (int, optional) – Number of frames to load. 0 to load everything after the offset. (Default: 0) - 要加载的帧数。

offset (int, optional) – Number of frames from the start of the file to begin data loading. (Default: 0) - 从文件开始到开始数据加载的帧数。

signalinfo (sox_signalinfo_t, optional) – A sox_signalinfo_t type, which could be helpful if the audio type cannot be automatically determined. (Default: None) - sox_signalinfo_t 类型,如果不能自动确定音频类型,这可能会有所帮助。

encodinginfo (sox_encodinginfo_t, optional) – A sox_encodinginfo_t type, which could be set if the audio type cannot be automatically determined. (Default: None) - sox_encodinginfo_t 类型,如果不能自动确定音频类型,则可以设置。

filetype (str, optional) – A filetype or extension to be set if sox cannot determine it automatically. (Default: None) - 如果 sox 无法自动确定要设置的文件类型或扩展名。

2.2 Returns

An output tensor of size [C x L] or [L x C] where L is the number of audio frames and C is the number of channels. An integer which is the sample rate of the audio (as listed in the metadata of the file)

2.3 Return type

Tuple[torch.Tensor, int]

2.4 Example

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# yongqiang chengfrom __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport torchaudio# WAV file
audio_file = "/mnt/f/yongqiang_work/ding.wav"data, sample_rate = torchaudio.load(audio_file)
print("data.size() =", data.size())
print("sample_rate =", sample_rate)data_normalized, sample_rate = torchaudio.load(audio_file, normalization=True)
print("data_normalized.size() =", data_normalized.size())
print("sample_rate =", sample_rate)
/home/yongqiang/miniconda3/envs/pt-1.4_py-3.6/bin/python /home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py
data.size() = torch.Size([2, 17504])
sample_rate = 44100
data_normalized.size() = torch.Size([2, 17504])
sample_rate = 44100Process finished with exit code 0

2.5 data, sample_rate = torchaudio.load(audio_file, normalization=False)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# yongqiang chengfrom __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport torchaudio# WAV file
audio_file = "/mnt/f/yongqiang_work/ding.wav"data, sample_rate = torchaudio.load(audio_file, normalization=False)
print("data.size() =", data.size())
print("sample_rate =", sample_rate)data = data.numpy()data_normalized, sample_rate = torchaudio.load(audio_file, normalization=True)
print("data_normalized.size() =", data_normalized.size())
print("sample_rate =", sample_rate)data_normalized = data_normalized.numpy()
/home/yongqiang/miniconda3/envs/pt-1.4_py-3.6/bin/python /home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py
data.size() = torch.Size([2, 17504])
sample_rate = 44100
data_normalized.size() = torch.Size([2, 17504])
sample_rate = 44100Process finished with exit code 0

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

2.6 data_normalized, sample_rate = torchaudio.load(audio_file, normalization=True)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# yongqiang chengfrom __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport torchaudio# WAV file
audio_file = "/mnt/f/yongqiang_work/ding.wav"data, sample_rate = torchaudio.load(audio_file, normalization=False)
print("data.size() =", data.size())
print("sample_rate =", sample_rate)data = data.numpy()data_normalized, sample_rate = torchaudio.load(audio_file, normalization=True)
print("data_normalized.size() =", data_normalized.size())
print("sample_rate =", sample_rate)data_normalized = data_normalized.numpy()print("yongqiang cheng")
/home/yongqiang/miniconda3/envs/pt-1.4_py-3.6/bin/python /home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py
data.size() = torch.Size([2, 17504])
sample_rate = 44100
data_normalized.size() = torch.Size([2, 17504])
sample_rate = 44100
yongqiang chengProcess finished with exit code 0

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

3. Python wave 读取音频数据

Python wave 读取音频数据,针对 sample width in bytes = 2 bytes,short / short int 可以表示的的最大范围是 [-32768, 32767],注意查看读取的数据。Python wave 同 torchaudio.load() 读取音频数据表示范围有区别,注意对比。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# yongqiang chengfrom __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport wave
import numpy as np
import matplotlib.pyplot as plt# WAV file
audio_file = "/mnt/f/yongqiang_work/ding.wav"
object = wave.open(audio_file, "rb")# (nchannels, sampwidth, framerate, nframes, comptype, compname)
params = object.getparams()
nchannels, sampwidth, framerate, nframes, comptype, compname = params[:6]
print("nchannels =", nchannels)
print("sampwidth =", sampwidth)
print("framerate =", framerate)
print("nframes =", nframes)
print("comptype =", comptype)
print("compname =", compname)# Returns number of audio channels (1 for mono, 2 for stereo).
print("object.getnchannels() =", object.getnchannels())# Returns sample width in bytes.
print("object.getsampwidth() =", object.getsampwidth())# Returns sampling frequency.
print("object.getframerate() =", object.getframerate())# Returns number of audio frames.
print("object.getnframes() =", object.getnframes())# Returns compression type ('NONE' is the only supported type).
print("object.getcomptype() =", object.getcomptype())# Human-readable version of getcomptype(). Usually 'not compressed' parallels 'NONE'.
print("object.getcompname() =", object.getcompname())# Reads and returns at most n frames of audio, as a bytes object.
str_data = object.readframes(nframes)
# nframes = 17504,  channels = 2, sampwidth = 2
# str_data (bytes: 70016) = nframes * channels * sampwidth = 17504 * 2 * 2 = 70016
num_bytes = len(str_data) # num_bytes = 70016
print("num_bytes =", num_bytes, "bytes")
object.close()wave_data = np.fromstring(str_data, dtype=np.short)
wave_data.shape = -1, 2
wave_data = wave_data.T
time = np.arange(0, nframes) * (1.0 / framerate)plt.subplot(211)
plt.plot(time, wave_data[0])
plt.xlabel("left channel - time (seconds)")
plt.subplot(212)
plt.plot(time, wave_data[1], c="g")
plt.xlabel("right channel - time (seconds)")
plt.show()
/home/yongqiang/miniconda3/envs/pt-1.4_py-3.6/bin/python /home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py
nchannels = 2
sampwidth = 2
framerate = 44100
nframes = 17504
comptype = NONE
compname = not compressed
object.getnchannels() = 2
object.getsampwidth() = 2
object.getframerate() = 44100
object.getnframes() = 17504
object.getcomptype() = NONE
object.getcompname() = not compressed
num_bytes = 70016 bytesProcess finished with exit code 0

在这里插入图片描述
short / short int 可以表示的的最大范围是 [-32768, 32767]
2^15 = 32768
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

4. 数据对比

  • torchaudio
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# yongqiang chengfrom __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport torchaudio# WAV file
audio_file = "/mnt/f/yongqiang_work/ding.wav"data, sample_rate = torchaudio.load(audio_file, normalization=False)
print("data.size() =", data.size())
print("sample_rate =", sample_rate)data = data.numpy()
print("data[0, 189:205] = ")
print(data[0, 189:205])
print("data[1, 189:205] = ")
print(data[1, 189:205])data_normalized, sample_rate = torchaudio.load(audio_file, normalization=True)
print("data_normalized.size() =", data_normalized.size())
print("sample_rate =", sample_rate)data_normalized = data_normalized.numpy()
print("data_normalized[0, 189:205] = ")
print(data_normalized[0, 189:205])
print("data_normalized[1, 189:205] = ")
print(data_normalized[1, 189:205])print("yongqiang cheng")
/home/yongqiang/miniconda3/envs/pt-1.4_py-3.6/bin/python /home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py
data.size() = torch.Size([2, 17504])
sample_rate = 44100
data[0, 189:205] = 
[    65536.   -131072.    131072.   -131072.    131072.   -262144.196608.   -327680.    327680.   -524288.    524288.  -1179648.5308416.   8847360.    196608. -19660800.]
data[1, 189:205] = 
[        0.   -131072.     65536.   -131072.    131072.   -131072.262144.   -262144.    262144.   -458752.    458752.  -1048576.4390912.   7602176.    327680. -16777216.]
data_normalized.size() = torch.Size([2, 17504])
sample_rate = 44100
data_normalized[0, 189:205] = 
[ 3.0517578e-05 -6.1035156e-05  6.1035156e-05 -6.1035156e-056.1035156e-05 -1.2207031e-04  9.1552734e-05 -1.5258789e-041.5258789e-04 -2.4414062e-04  2.4414062e-04 -5.4931641e-042.4719238e-03  4.1198730e-03  9.1552734e-05 -9.1552734e-03]
data_normalized[1, 189:205] = 
[ 0.0000000e+00 -6.1035156e-05  3.0517578e-05 -6.1035156e-056.1035156e-05 -6.1035156e-05  1.2207031e-04 -1.2207031e-041.2207031e-04 -2.1362305e-04  2.1362305e-04 -4.8828125e-042.0446777e-03  3.5400391e-03  1.5258789e-04 -7.8125000e-03]
yongqiang chengProcess finished with exit code 0
  • Python wave
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# yongqiang chengfrom __future__ import absolute_import
from __future__ import division
from __future__ import print_functionimport wave
import numpy as np
import matplotlib.pyplot as plt# WAV file
audio_file = "/mnt/f/yongqiang_work/ding.wav"
object = wave.open(audio_file, "rb")# (nchannels, sampwidth, framerate, nframes, comptype, compname)
params = object.getparams()
nchannels, sampwidth, framerate, nframes, comptype, compname = params[:6]
print("nchannels =", nchannels)
print("sampwidth =", sampwidth)
print("framerate =", framerate)
print("nframes =", nframes)
print("comptype =", comptype)
print("compname =", compname)# Returns number of audio channels (1 for mono, 2 for stereo).
print("object.getnchannels() =", object.getnchannels())# Returns sample width in bytes.
print("object.getsampwidth() =", object.getsampwidth())# Returns sampling frequency.
print("object.getframerate() =", object.getframerate())# Returns number of audio frames.
print("object.getnframes() =", object.getnframes())# Returns compression type ('NONE' is the only supported type).
print("object.getcomptype() =", object.getcomptype())# Human-readable version of getcomptype(). Usually 'not compressed' parallels 'NONE'.
print("object.getcompname() =", object.getcompname())# Reads and returns at most n frames of audio, as a bytes object.
str_data = object.readframes(nframes)
# nframes = 17504,  channels = 2, sampwidth = 2
# str_data (bytes: 70016) = nframes * channels * sampwidth = 17504 * 2 * 2 = 70016
num_bytes = len(str_data) # num_bytes = 70016
print("num_bytes =", num_bytes, "bytes")
object.close()wave_data = np.fromstring(str_data, dtype=np.short)
wave_data.shape = -1, 2
wave_data = wave_data.T
time = np.arange(0, nframes) * (1.0 / framerate)plt.subplot(211)
plt.plot(time, wave_data[0])
plt.xlabel("left channel - time (seconds)")
plt.subplot(212)
plt.plot(time, wave_data[1], c="g")
plt.xlabel("right channel - time (seconds)")
plt.show()print("wave_data[0, 189:205] = ")
print(wave_data[0, 189:205])
print("wave_data[1, 189:205] = ")
print(wave_data[1, 189:205])print("yongqiang cheng")
/home/yongqiang/miniconda3/envs/pt-1.4_py-3.6/bin/python /home/yongqiang/pytorch_work/end2end-asr-pytorch-example/yongqiang.py
nchannels = 2
sampwidth = 2
framerate = 44100
nframes = 17504
comptype = NONE
compname = not compressed
object.getnchannels() = 2
object.getsampwidth() = 2
object.getframerate() = 44100
object.getnframes() = 17504
object.getcomptype() = NONE
object.getcompname() = not compressed
num_bytes = 70016 bytes
wave_data[0, 189:205] = 
[   1   -2    2   -2    2   -4    3   -5    5   -8    8  -18   81  1353 -300]
wave_data[1, 189:205] = 
[   0   -2    1   -2    2   -2    4   -4    4   -7    7  -16   67  1165 -256]
yongqiang chengProcess finished with exit code 0

4.1 data, sample_rate = torchaudio.load(audio_file, normalization=False)

针对 sample width in bytes = 2 bytes,4.1 中数据为 4.3 中对应原始数据乘以 2^16 = 65536

data[0, 189:205] = 
[    65536.   -131072.    131072.   -131072.131072.   -262144.    196608.   -327680.327680.   -524288.    524288.  -1179648.5308416.   8847360.    196608. -19660800.]data[1, 189:205] = 
[        0.   -131072.     65536.   -131072.131072.   -131072.    262144.   -262144.262144.   -458752.    458752.  -1048576.4390912.   7602176.    327680. -16777216.]

2^31 = 2147483648
2^16 = 65536
2^15 = 32768

4.2 data_normalized, sample_rate = torchaudio.load(audio_file, normalization=True)

4.2 中归一化数据为 4.1 中对应数据除以 2^31 = 2147483648。针对 sample width in bytes = 2 bytes,4.2 中数据为 4.3 中对应原始数据除以 2^(31 - 16) = 2^15 = 32768

data_normalized[0, 189:205] = 
[ 3.0517578e-05 -6.1035156e-05  6.1035156e-05 -6.1035156e-056.1035156e-05 -1.2207031e-04  9.1552734e-05 -1.5258789e-041.5258789e-04 -2.4414062e-04  2.4414062e-04 -5.4931641e-042.4719238e-03  4.1198730e-03  9.1552734e-05 -9.1552734e-03]data_normalized[1, 189:205] = 
[ 0.0000000e+00 -6.1035156e-05  3.0517578e-05 -6.1035156e-056.1035156e-05 -6.1035156e-05  1.2207031e-04 -1.2207031e-041.2207031e-04 -2.1362305e-04  2.1362305e-04 -4.8828125e-042.0446777e-03  3.5400391e-03  1.5258789e-04 -7.8125000e-03]

4.3 Python wave

针对 sample width in bytes = 2 bytes,4.1 中数据为 4.3 中对应原始数据乘以 2^16 = 65536

wave_data[0, 189:205] = 
[   1   -2    2   -22   -4    3   -55   -8    8  -1881  135    3 -300]wave_data[1, 189:205] = 
[   0   -2    1   -22   -2    4   -44   -7    7  -1667  116    5 -256]

这篇关于torchaudio - Python wave 读取音频数据对比的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/401878

相关文章

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

python处理带有时区的日期和时间数据

《python处理带有时区的日期和时间数据》这篇文章主要为大家详细介绍了如何在Python中使用pytz库处理时区信息,包括获取当前UTC时间,转换为特定时区等,有需要的小伙伴可以参考一下... 目录时区基本信息python datetime使用timezonepandas处理时区数据知识延展时区基本信息

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1