采集数据->采样率调整

  1. 使用torchaudio进行重采样(cpu版)
    • 首先导入相关包,既然使用torch作为我们的选项,安装torch环境我就不必多说了,如果你不想用torch可以使用后文提到的另一个库

      1 import torch
      2 import torchaudio
      3 from torchaudio.transforms import Resample
      4 from time import time#仅计算时间,不影响主体
    • 使用torchaudio.load导入音频文件

    • 设定目标采样率并构造resample函数

    • 调用构造好的resample函数

    • 调用torchaudio的保存函数

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

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

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

    1. 使用使用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都知道它的强大,更多是用于后续的操作说是。

    2. 使用librosa库进行重采样

      具体步骤:

      • 导入两个库文件,librosa和音频文件读写库soundfile

        import librosa
        import soundfile as sf
        from time import time#仅计算时间,不影响主体
      • 导入音频文件

      • 设定目标采样率

      • 重采样

      • 输出

      综合封装成函数:

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

      总结:

      • 优点,简单小巧,ibrosa有很多能处理音频的功能

      • 缺点:无法调用cuda,保存的时候需要依赖soundfile库。

      • 时间:也是几秒左右,和torchaudiocpu版差不多

      • 小声bb:提取32k的效果好像没有torchaudio好【嘛,毕竟librosa历史有点久了,没有专注深度学习的torch好很正常啦】,你们也可以自己测一下

    all code:

     1 import torch
    2 import torchaudio
    3 from torchaudio.transforms import Resample
    4 import librosa
    5 import soundfile as sf
    6 from time import time
    7 ​
    8 def resample_by_cpu():
    9 file_path = input("please input your file path: ")
    10 start_time = time()
    11 y, sr = torchaudio.load(file_path) #使用torchaudio.load导入音频文件
    12 ​
    13 target_sample = 32000 #设定目标采样率
    14 resampler = Resample(orig_freq=sr, new_freq=target_sample)#构造resample函数,输入原始采样率和目标采样率
    15 resample_misic = resampler(y) #调用resample函数
    16 ​
    17 torchaudio.save("test.mp3", resample_misic, target_sample)#调用torchaudio的保存即可
    18 print(f"cost :{time() - start_time}s")
    19 def resample_use_cuda():
    20 ​
    21 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    22 start_time = time()
    23 file_path = input("please input your file path:")
    24 y, sr = torchaudio.load(file_path)
    25 ​
    26 y = y.to(device)
    27 target_sample = 32000
    28 resampler = Resample(orig_freq=sr, new_freq=target_sample).to(device)
    29 resample_misic = resampler(y)
    30 torchaudio.save("test.mp3", resample_misic.to('cpu'), target_sample)
    31 print(f"cost :{time() - start_time}s")
    32 ​
    33 def resample_by_lisa():
    34 file_path = input("please input your file path:")
    35 start_time = time()
    36 y, sr = librosa.load(file_path)#使用librosa导入音频文件
    37 target_sample_rate = 32000
    38 y_32k = librosa.resample(y=y, orig_sr=sr, target_sr=target_sample_rate)#使用librosa进行重采样至目标采样率
    39 sf.write("test_lisa.mp3", data=y_32k, samplerate=target_sample_rate)#使用soundfile进行文件写入
    40 print(f"cost :{time() - start_time}s")
    41 ​
    42 if __name__ == '__main__':
    43 resample_use_cuda()
    44 resample_by_cpu()
    45 resample_by_lisa()

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

  1. 使用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')

  2. 使用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:

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

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

    • 输出:

  3. 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 音频处理(1)——重采样、音高提取的更多相关文章

  1. Python即时网络爬虫项目: 内容提取器的定义(Python2.7版本)

    1. 项目背景 在Python即时网络爬虫项目启动说明中我们讨论一个数字:程序员浪费在调测内容提取规则上的时间太多了(见上图),从而我们发起了这个项目,把程序员从繁琐的调测规则中解放出来,投入到更高端 ...

  2. python操作三大主流数据库(5)python操作mysql⑤使用Jinja2模板提取优化页面展示

    python操作mysql⑤使用Jinja2模板提取优化页面展示 在templates目录下的index.html.cat.html等页面有一些共同的元素,代码比较冗余可以使用模板提取公共代码,在各网 ...

  3. 『开发技巧』Python音频操作工具PyAudio上手教程

    『开发技巧』Python音频操作工具PyAudio上手教程 ​ 0.引子 当需要使用Python处理音频数据时,使用python读取与播放声音必不可少,下面介绍一个好用的处理音频PyAudio工具包. ...

  4. < python音频库:Windows下pydub安装配置、过程出现的问题及常用API >

    < python音频库:Windows下pydub安装配置.过程出现的问题及常用API > 背景 刚从B站上看过倒放挑战之后也想体验下,心血来潮一个晚上完成了基本的实现.其中倒放与播放部分 ...

  5. Python音频操作+同时播放两个音频

    对于python而言,音频的操作可以使用pygame包中的sound 和 music对象,本博客主要讲解这两个对象. 1.sound对象 Sound对象适合处理较短的音乐,如OGG和WAV格式的音频文 ...

  6. python音频处理相关类库

    一.eyeD3 以下是eyed3的官方介绍 eyeD3 is a Python tool for working with audio files, specifically mp3 files co ...

  7. Python即时网络爬虫项目: 内容提取器的定义

    1. 项目背景 在python 即时网络爬虫项目启动说明中我们讨论一个数字:程序员浪费在调测内容提取规则上的时间,从而我们发起了这个项目,把程序员从繁琐的调测规则中解放出来,投入到更高端的数据处理工作 ...

  8. python音频处理用到的操作

    作者:桂. 时间:2017-05-03  12:18:46 链接:http://www.cnblogs.com/xingshansi/p/6799994.html 前言 本文主要记录python下音频 ...

  9. 短文本分析----基于python的TF-IDF特征词标签自动化提取

    绪论 最近做课题,需要分析短文本的标签,在短时间内学习了自然语言处理,社会标签推荐等非常时髦的技术.我们的需求非常类似于从大量短文本中获取关键词(融合社会标签和时间属性)进行用户画像.这一切的基础就是 ...

  10. Python爬虫10-页面解析数据提取思路方法与简单正则应用

    GitHub代码练习地址:正则1:https://github.com/Neo-ML/PythonPractice/blob/master/SpiderPrac15_RE1.py 正则2:match. ...

随机推荐

  1. itest(爱测试)开源接口测试&敏捷测试&极简项目管理 7.1.0 发布,ui优化及bug修复

    (一)itest 简介及更新说明 itest 开源敏捷测试管理,testOps 践行者,极简的任务管理,测试管理,缺陷管理,测试环境管理,接口测试,接口Mock 6合1,又有丰富的统计分析.可按测试包 ...

  2. uniapp 返回顶部

    <template> <view> <view class="btn" @tap="toTop" :style="{'d ...

  3. Centos7安装Nginx教程,一步安装http和https

    nginx是一款轻量级web服务器,主要有负载均衡和反向代理的特性. 安装准备 nginx一些模块需要依赖lib库,所以先安装lib库,执行以下命令: [root@localhost local]# ...

  4. jquery的筛选器

    <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8 ...

  5. 剑指Offer-53.表示数值的字符串(C++/Java)

    题目: 请实现一个函数用来判断字符串是否表示数值(包括整数和小数).例如,字符串"+100","5e2","-123","3.14 ...

  6. LVGL8文本框设置长文本会自动滚动到文本最后解决方法

    在创建完成并设置完文本之后加一句 lv_obj_scroll_to_y(obj,0, LV_ANIM_OFF); 就可以了 原因:官方控件里面设置文本的接口里面设置文本后会设置一次光标位置到文本末尾, ...

  7. Vue学习:20.综合案例-商品列表

    学而时用之,方能融会贯通! 实例:商品列表 实现功能 要求表格组件支持动态数据渲染.自定义表头和主体.标签组件需要双击显示输入框并获得焦点,可以编辑标签信息. 思路 首先是表格组件,动态渲染需要使用组 ...

  8. == 和 equals 的区别是什么

    == : 它的作用是判断两个对象的地址是不是相等.即,判断两个对象是不是同一个对象.(基本数据类型 == 比较的是值,引用数据类型 == 比较的是内存地址) equals() : 它的作用也是判断两个 ...

  9. 在 Visual Studio 2022 (Visual C++ 17) 中使用 Visual Leak Detector

    1 问题描述 1.1 内存泄漏的困扰和解决之道 在C/C++程序开发过程中,开发者受益于C/C++的强大,与此同时也承受着C/C++程序开发的额外风险.像Java.C#这类带GC(内存垃圾回收)的编程 ...

  10. 利用 device_map、torch.dtype、bitsandbytes 压缩模型参数控制使用设备

    为了更好的阅读体验,请点击这里 device_map 以下内容参考 Huggingface Accelerate文档:超大模型推理方法 在 HuggingFace 中有个重要的关键字是 device_ ...