python 音频处理重采样、音高提取的操作方法

 更新时间:2024年08月02日 09:54:06   作者:io_T_T  
这篇文章主要介绍了python 音频处理重采样、音高提取,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧

采集数据->采样率调整

  • 使用torchaudio进行重采样(cpu版)

    • 首先导入相关包,既然使用torch作为我们的选项,安装torch环境我就不必多说了,如果你不想用torch可以使用后文提到的另一个库

import torch
 import torchaudio
 from torchaudio.transforms import Resample
 from time import time#仅计算时间,不影响主体
  • 使用torchaudio.load导入音频文件
  • 设定目标采样率并构造resample函数
  • 调用构造好的resample函数
  • 调用torchaudio的保存函数

封装一下,总函数【记得先导入】:

def resample_by_cpu():
    file_path = input("please input your file path: ")
    start_time = time()#不影响,可去掉
    y, sr = torchaudio.load(file_path)  #使用torchaudio.load导入音频文件
​
    target_sample = 32000   #设定目标采样率
    resampler = Resample(orig_freq=sr, new_freq=target_sample)#构造resample函数,输入原始采样率和目标采样率
    resample_misic = resampler(y)                             #调用resample函数
​
    torchaudio.save("test.mp3", resample_misic, target_sample)#调用torchaudio的保存即可
    print(f"cost :{time() - start_time}s")#不影响,可去掉

最后结果大概是几秒钟这样子

2.使用使用torchaudio进行重采样(gpu版):

有了上面cpu的基础,其实调用gpu也就更换一下设备,和放入gpu的操作就好了,因此不过多赘述

def resample_use_cuda():
​
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    start_time = time()
    file_path = input("please input your file path:")
    y, sr = torchaudio.load(file_path)
​
    y = y.to(device)
    target_sample = 32000
    resampler = Resample(orig_freq=sr, new_freq=target_sample).to(device)
    resample_misic = resampler(y)
    torchaudio.save("test.mp3", resample_misic.to('cpu'), target_sample)    #这里注意要把结果从gpu中拿出来到cpu,不然会报错。
    print(f"cost :{time() - start_time}s")

时间方面嘛,单个音频多了放入gpu取出gpu的步骤肯定会稍慢的,但是跑过cuda都知道它的强大,更多是用于后续的操作说是。

3.使用librosa库进行重采样

具体步骤:

  • 导入两个库文件,librosa和音频文件读写库soundfile
import librosa
import soundfile as sf
from time import time#仅计算时间,不影响主体
  • 导入音频文件
  • 设定目标采样率
  • 重采样
  • 输出

综合封装成函数:

def resample_by_lisa():
    file_path = input("please input your file path:")
    start_time = time()
    y, sr = librosa.load(file_path)     #使用librosa导入音频文件
    target_sample_rate = 32000
    y_32k = librosa.resample(y=y, orig_sr=sr, target_sr=target_sample_rate)         #使用librosa进行重采样至目标采样率
    sf.write("test_lisa.mp3", data=y_32k, samplerate=target_sample_rate)        #使用soundfile进行文件写入
    print(f"cost :{time() - start_time}s")

总结:

  • 优点,简单小巧,ibrosa有很多能处理音频的功能
  • 缺点:无法调用cuda,保存的时候需要依赖soundfile库。
  • 时间:也是几秒左右,和torchaudiocpu版差不多
  • 小声bb:提取32k的效果好像没有torchaudio好【嘛,毕竟librosa历史有点久了,没有专注深度学习的torch好很正常啦】,你们也可以自己测一下

all code:

import torch
import torchaudio
from torchaudio.transforms import Resample
import librosa
import soundfile as sf
from time import time
​
def resample_by_cpu():
    file_path = input("please input your file path: ")
    start_time = time()
    y, sr = torchaudio.load(file_path)  #使用torchaudio.load导入音频文件
​
    target_sample = 32000   #设定目标采样率
    resampler = Resample(orig_freq=sr, new_freq=target_sample)#构造resample函数,输入原始采样率和目标采样率
    resample_misic = resampler(y)                             #调用resample函数
​
    torchaudio.save("test.mp3", resample_misic, target_sample)#调用torchaudio的保存即可
    print(f"cost :{time() - start_time}s")
def resample_use_cuda():
​
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    start_time = time()
    file_path = input("please input your file path:")
    y, sr = torchaudio.load(file_path)
​
    y = y.to(device)
    target_sample = 32000
    resampler = Resample(orig_freq=sr, new_freq=target_sample).to(device)
    resample_misic = resampler(y)
    torchaudio.save("test.mp3", resample_misic.to('cpu'), target_sample)
    print(f"cost :{time() - start_time}s")
​
def resample_by_lisa():
    file_path = input("please input your file path:")
    start_time = time()
    y, sr = librosa.load(file_path)#使用librosa导入音频文件
    target_sample_rate = 32000
    y_32k = librosa.resample(y=y, orig_sr=sr, target_sr=target_sample_rate)#使用librosa进行重采样至目标采样率
    sf.write("test_lisa.mp3", data=y_32k, samplerate=target_sample_rate)#使用soundfile进行文件写入
    print(f"cost :{time() - start_time}s")
​
if __name__ == '__main__':
    resample_use_cuda()
    resample_by_cpu()
    resample_by_lisa()

2.2 提取pitch基频特征【音高提取】

使用torchaudio进行基频特征提取

其实主要使用的这个函数:torchaudio.transforms._transforms.PitchShift

让我们来看看它官方的example,仿照着来写就好啦

>>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
>>> transform = transforms.PitchShift(sample_rate, 4)
>>> waveform_shift = transform(waveform)  # (channel, time)

步骤:

  • 导入依赖
import torchaudio
import torchaudio.transforms as Tf
import matplotlib.pyplot as plt     #画图依赖
  • 导入音频
  • 构造PitchShift
  • 使用这个函数对歌曲进行基频提取

code:

def get_pitch_by_torch():
    file_path = input("file path:")
    y, sr = torchaudio.load(file_path)
    """specimen:
    >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
    >>> transform = transforms.PitchShift(sample_rate, 4)
    >>> waveform_shift = transform(waveform)  # (channel, time)
    """
    pitch_tf = Tf.PitchShift(sample_rate=sr, n_steps=0)
    feature = pitch_tf(y)
    # 绘制基频特征 这部分可以忽略,只是画图而已,可以直接复制不用理解
    plt.figure(figsize=(16, 5))
    plt.plot(feature[0].numpy(), label='Pitch')
    plt.xlabel('Frame')
    plt.ylabel('Frequency (Hz)')
    plt.title('Pitch Estimation')
    plt.legend()
    plt.show()

输出图片【总歌曲】效果:

将输出的范围稍微改一下,切分特征的一部分,就是歌曲部分的音高特征啦,效果就很明显了

改为:plt.plot(feature[0][5000:10000].numpy(), label='Pitch')

使用librosa提取基频特征

  • 步骤:
    • 导入包
    • 提取基频特征
    • (可选)绘制基频特征

主要函数:librosa.pyin,请见官方example

#Computing a fundamental frequency (F0) curve from an audio input
>>> y, sr = librosa.load(librosa.ex('trumpet'))
>>> f0, voiced_flag, voiced_probs = librosa.pyin(y,
...                                              sr=sr,
...                                              fmin=librosa.note_to_hz('C2'),
...                                              fmax=librosa.note_to_hz('C7'))
>>> times = librosa.times_like(f0, sr=sr)

code:

def get_pitch_by_librosa():
​
    file_path = input("请输入音频文件路径:")
    y, sr = librosa.load(file_path)
    """librosa.pyin(y,sr=sr,fmin=librosa.note_to_hz('C2'),fmax=librosa.note_to_hz('C7'))"""
    # 使用pyin提取基频特征
    f0, voiced_flag, voiced_probs = librosa.pyin(y, sr=sr, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))
​
    # 绘制基频特征,可忽略
    plt.figure(figsize=(14, 5))
    librosa.display.waveshow(y, sr=sr, alpha=0.5)
    plt.plot(librosa.times_like(f0), f0, label='f0 (fundamental frequency)', color='r')
    plt.xlabel('Time (s)')
    plt.ylabel('Frequency (Hz)')
    plt.title('Pitch (fundamental frequency) Estimation')
    plt.legend()
    plt.show()

总结:

  • 比torchaudio略微麻烦一点,不过多了两个参数 voiced_flag, voiced_probs,看起来的视觉图好像也有些不一样,不过都是按照官方的这个来了,这也不对的话我也不会了

输出:

all code:

import torchaudio
import torchaudio.transforms as Tf
import matplotlib.pyplot as plt
import librosa
def get_pitch_by_torch():
    file_path = input("file path:")
    y, sr = torchaudio.load(file_path)
    """specimen:
    >>> waveform, sample_rate = torchaudio.load("test.wav", normalize=True)
    >>> transform = transforms.PitchShift(sample_rate, 4)
    >>> waveform_shift = transform(waveform)  # (channel, time)
    """
    pitch_tf = Tf.PitchShift(sample_rate=sr, n_steps=0)
    feature = pitch_tf(y)
    # 绘制基频特征
    plt.figure(figsize=(16, 5))
    plt.plot(feature[0][5000:10000].numpy(), label='Pitch')
    plt.xlabel('Frame')
    plt.ylabel('Frequency (Hz)')
    plt.title('Pitch Estimation')
    plt.legend()
    plt.show()
def get_pitch_by_librosa():
​
    file_path = input("请输入音频文件路径:")
    y, sr = librosa.load(file_path)
    """librosa.pyin(y,sr=sr,fmin=librosa.note_to_hz('C2'),fmax=librosa.note_to_hz('C7'))"""
    # 使用pyin提取基频特征
    f0, voiced_flag, voiced_probs = librosa.pyin(y, sr=sr, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))
​
    # 绘制基频特征,可忽略
    plt.figure(figsize=(14, 5))
    librosa.display.waveshow(y, sr=sr, alpha=0.5)
    plt.plot(librosa.times_like(f0), f0, label='f0 (fundamental frequency)', color='r')
    plt.xlabel('Time (s)')
    plt.ylabel('Frequency (Hz)')
    plt.title('Pitch (fundamental frequency) Estimation')
    plt.legend()
    plt.show()
if __name__ == '__main__':
    # get_pitch_by_torch()
    # get_pitch_by_librosa()

后续PPG特征、vec特征见下一章 

到此这篇关于python 音频处理重采样、音高提取的文章就介绍到这了,更多相关python 音频重采样内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 一篇文章搞懂Python的文件路径操作

    一篇文章搞懂Python的文件路径操作

    这篇文章主要给大家介绍了关于Python文件路径操作的相关资料,在python中我们会经常的对文件使用路径,文件路径通常有两种,分别为绝对路径、相对路径,需要的朋友可以参考下
    2023-07-07
  • 深入解析NumPy中的Broadcasting广播机制

    深入解析NumPy中的Broadcasting广播机制

    在吴恩达老师的深度学习专项课程中,老师有提到NumPy中的广播机制,同时那一周的测验也有涉及到广播机制的题目。那么,到底什么是NumPy中的广播机制?本文就来介绍一下
    2021-05-05
  • python直接获取API传递回来的参数方法

    python直接获取API传递回来的参数方法

    今天小编就为大家分享一篇python直接获取API传递回来的参数方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-12-12
  • python去除空格和换行符的实现方法(推荐)

    python去除空格和换行符的实现方法(推荐)

    下面小编就为大家带来一篇python去除空格和换行符的实现方法(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-01-01
  • python绘图模块之利用turtle画图

    python绘图模块之利用turtle画图

    这篇文章主要给大家介绍了关于python模块教程之利用turtle画图的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • python 模拟登陆163邮箱

    python 模拟登陆163邮箱

    这篇文章主要介绍了python 模拟登陆163邮箱的示例,帮助大家更好的理解和使用python,感兴趣的朋友可以了解下
    2020-12-12
  • Python代码实现KNN算法

    Python代码实现KNN算法

    这篇文章主要为大家详细介绍了Python代码实现KNN算法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-12-12
  • Python脚本支持OC代码重构模块调用关系分析实践

    Python脚本支持OC代码重构模块调用关系分析实践

    在软件开发中,经常会遇到一些代码问题,例如逻辑结构复杂、依赖关系混乱、代码冗余、不易读懂的命名等,这些问题可能导致代码的可维护性下降,增加维护成本,同时也会影响到开发效率,本文以Python实现自动化的工具,支持代码重构过程的实践
    2023-10-10
  • 详细过程带你用Python做车牌自动识别系统

    详细过程带你用Python做车牌自动识别系统

    这篇文章主要介绍了带你用Python做车牌自动识别系统的详细过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-08-08
  • Python实现合并两个列表的方法分析

    Python实现合并两个列表的方法分析

    这篇文章主要介绍了Python实现合并两个列表的方法,结合实例形式对比分析了常见的Python列表合并操作技巧,需要的朋友可以参考下
    2018-05-05

最新评论