最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python 音頻處理重采樣、音高提取的操作方法

 更新時(shí)間:2024年08月02日 09:54:06   作者:io_T_T  
這篇文章主要介紹了python 音頻處理重采樣、音高提取,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧

采集數(shù)據(jù)->采樣率調(diào)整

  • 使用torchaudio進(jìn)行重采樣(cpu版)

    • 首先導(dǎo)入相關(guān)包,既然使用torch作為我們的選項(xiàng),安裝torch環(huán)境我就不必多說了,如果你不想用torch可以使用后文提到的另一個(gè)庫(kù)

import torch
 import torchaudio
 from torchaudio.transforms import Resample
 from time import time#僅計(jì)算時(shí)間,不影響主體
  • 使用torchaudio.load導(dǎo)入音頻文件
  • 設(shè)定目標(biāo)采樣率并構(gòu)造resample函數(shù)
  • 調(diào)用構(gòu)造好的resample函數(shù)
  • 調(diào)用torchaudio的保存函數(shù)

封裝一下,總函數(shù)【記得先導(dǎo)入】:

def resample_by_cpu():
    file_path = input("please input your file path: ")
    start_time = time()#不影響,可去掉
    y, sr = torchaudio.load(file_path)  #使用torchaudio.load導(dǎo)入音頻文件
?
    target_sample = 32000   #設(shè)定目標(biāo)采樣率
    resampler = Resample(orig_freq=sr, new_freq=target_sample)#構(gòu)造resample函數(shù),輸入原始采樣率和目標(biāo)采樣率
    resample_misic = resampler(y)                             #調(diào)用resample函數(shù)
?
    torchaudio.save("test.mp3", resample_misic, target_sample)#調(diào)用torchaudio的保存即可
    print(f"cost :{time() - start_time}s")#不影響,可去掉

最后結(jié)果大概是幾秒鐘這樣子

2.使用使用torchaudio進(jìn)行重采樣(gpu版):

有了上面cpu的基礎(chǔ),其實(shí)調(diào)用gpu也就更換一下設(shè)備,和放入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)    #這里注意要把結(jié)果從gpu中拿出來到cpu,不然會(huì)報(bào)錯(cuò)。
    print(f"cost :{time() - start_time}s")

時(shí)間方面嘛,單個(gè)音頻多了放入gpu取出gpu的步驟肯定會(huì)稍慢的,但是跑過cuda都知道它的強(qiáng)大,更多是用于后續(xù)的操作說是。

3.使用librosa庫(kù)進(jìn)行重采樣

具體步驟:

  • 導(dǎo)入兩個(gè)庫(kù)文件,librosa和音頻文件讀寫庫(kù)soundfile
import librosa
import soundfile as sf
from time import time#僅計(jì)算時(shí)間,不影響主體
  • 導(dǎo)入音頻文件
  • 設(shè)定目標(biāo)采樣率
  • 重采樣
  • 輸出

綜合封裝成函數(shù):

def resample_by_lisa():
    file_path = input("please input your file path:")
    start_time = time()
    y, sr = librosa.load(file_path)     #使用librosa導(dǎo)入音頻文件
    target_sample_rate = 32000
    y_32k = librosa.resample(y=y, orig_sr=sr, target_sr=target_sample_rate)         #使用librosa進(jìn)行重采樣至目標(biāo)采樣率
    sf.write("test_lisa.mp3", data=y_32k, samplerate=target_sample_rate)        #使用soundfile進(jìn)行文件寫入
    print(f"cost :{time() - start_time}s")

總結(jié):

  • 優(yōu)點(diǎn),簡(jiǎn)單小巧,ibrosa有很多能處理音頻的功能
  • 缺點(diǎn):無法調(diào)用cuda,保存的時(shí)候需要依賴soundfile庫(kù)。
  • 時(shí)間:也是幾秒左右,和torchaudiocpu版差不多
  • 小聲bb:提取32k的效果好像沒有torchaudio好【嘛,畢竟librosa歷史有點(diǎn)久了,沒有專注深度學(xué)習(xí)的torch好很正常啦】,你們也可以自己測(cè)一下

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導(dǎo)入音頻文件
?
    target_sample = 32000   #設(shè)定目標(biāo)采樣率
    resampler = Resample(orig_freq=sr, new_freq=target_sample)#構(gòu)造resample函數(shù),輸入原始采樣率和目標(biāo)采樣率
    resample_misic = resampler(y)                             #調(diào)用resample函數(shù)
?
    torchaudio.save("test.mp3", resample_misic, target_sample)#調(diào)用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導(dǎo)入音頻文件
    target_sample_rate = 32000
    y_32k = librosa.resample(y=y, orig_sr=sr, target_sr=target_sample_rate)#使用librosa進(jìn)行重采樣至目標(biāo)采樣率
    sf.write("test_lisa.mp3", data=y_32k, samplerate=target_sample_rate)#使用soundfile進(jìn)行文件寫入
    print(f"cost :{time() - start_time}s")
?
if __name__ == '__main__':
    resample_use_cuda()
    resample_by_cpu()
    resample_by_lisa()

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

使用torchaudio進(jìn)行基頻特征提取

其實(shí)主要使用的這個(gè)函數(shù):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)

步驟:

  • 導(dǎo)入依賴
import torchaudio
import torchaudio.transforms as Tf
import matplotlib.pyplot as plt     #畫圖依賴
  • 導(dǎo)入音頻
  • 構(gòu)造PitchShift
  • 使用這個(gè)函數(shù)對(duì)歌曲進(jìn)行基頻提取

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)
    # 繪制基頻特征 這部分可以忽略,只是畫圖而已,可以直接復(fù)制不用理解
    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提取基頻特征

  • 步驟:
    • 導(dǎo)入包
    • 提取基頻特征
    • (可選)繪制基頻特征

主要函數(shù):librosa.pyin,請(qǐng)見官方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("請(qǐng)輸入音頻文件路徑:")
    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()

總結(jié):

  • 比torchaudio略微麻煩一點(diǎn),不過多了兩個(gè)參數(shù) voiced_flag, voiced_probs,看起來的視覺圖好像也有些不一樣,不過都是按照官方的這個(gè)來了,這也不對(duì)的話我也不會(huì)了

輸出:

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("請(qǐng)輸入音頻文件路徑:")
    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()

后續(xù)PPG特征、vec特征見下一章 

到此這篇關(guān)于python 音頻處理重采樣、音高提取的文章就介紹到這了,更多相關(guān)python 音頻重采樣內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

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

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

    這篇文章主要給大家介紹了關(guān)于Python文件路徑操作的相關(guān)資料,在python中我們會(huì)經(jīng)常的對(duì)文件使用路徑,文件路徑通常有兩種,分別為絕對(duì)路徑、相對(duì)路徑,需要的朋友可以參考下
    2023-07-07
  • 深入解析NumPy中的Broadcasting廣播機(jī)制

    深入解析NumPy中的Broadcasting廣播機(jī)制

    在吳恩達(dá)老師的深度學(xué)習(xí)專項(xiàng)課程中,老師有提到NumPy中的廣播機(jī)制,同時(shí)那一周的測(cè)驗(yàn)也有涉及到廣播機(jī)制的題目。那么,到底什么是NumPy中的廣播機(jī)制?本文就來介紹一下
    2021-05-05
  • python直接獲取API傳遞回來的參數(shù)方法

    python直接獲取API傳遞回來的參數(shù)方法

    今天小編就為大家分享一篇python直接獲取API傳遞回來的參數(shù)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • python去除空格和換行符的實(shí)現(xiàn)方法(推薦)

    python去除空格和換行符的實(shí)現(xiàn)方法(推薦)

    下面小編就為大家?guī)硪黄猵ython去除空格和換行符的實(shí)現(xiàn)方法(推薦)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-01-01
  • python繪圖模塊之利用turtle畫圖

    python繪圖模塊之利用turtle畫圖

    這篇文章主要給大家介紹了關(guān)于python模塊教程之利用turtle畫圖的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • python 模擬登陸163郵箱

    python 模擬登陸163郵箱

    這篇文章主要介紹了python 模擬登陸163郵箱的示例,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-12-12
  • Python代碼實(shí)現(xiàn)KNN算法

    Python代碼實(shí)現(xiàn)KNN算法

    這篇文章主要為大家詳細(xì)介紹了Python代碼實(shí)現(xiàn)KNN算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Python腳本支持OC代碼重構(gòu)模塊調(diào)用關(guān)系分析實(shí)踐

    Python腳本支持OC代碼重構(gòu)模塊調(diào)用關(guān)系分析實(shí)踐

    在軟件開發(fā)中,經(jīng)常會(huì)遇到一些代碼問題,例如邏輯結(jié)構(gòu)復(fù)雜、依賴關(guān)系混亂、代碼冗余、不易讀懂的命名等,這些問題可能導(dǎo)致代碼的可維護(hù)性下降,增加維護(hù)成本,同時(shí)也會(huì)影響到開發(fā)效率,本文以Python實(shí)現(xiàn)自動(dòng)化的工具,支持代碼重構(gòu)過程的實(shí)踐
    2023-10-10
  • 詳細(xì)過程帶你用Python做車牌自動(dòng)識(shí)別系統(tǒng)

    詳細(xì)過程帶你用Python做車牌自動(dòng)識(shí)別系統(tǒng)

    這篇文章主要介紹了帶你用Python做車牌自動(dòng)識(shí)別系統(tǒng)的詳細(xì)過程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • Python實(shí)現(xiàn)合并兩個(gè)列表的方法分析

    Python實(shí)現(xiàn)合并兩個(gè)列表的方法分析

    這篇文章主要介紹了Python實(shí)現(xiàn)合并兩個(gè)列表的方法,結(jié)合實(shí)例形式對(duì)比分析了常見的Python列表合并操作技巧,需要的朋友可以參考下
    2018-05-05

最新評(píng)論

河南省| 淳安县| 兴安盟| 巫溪县| 武鸣县| 建阳市| 清河县| 肥西县| 保山市| 霞浦县| 项城市| 兖州市| 张掖市| 丰原市| 乌拉特后旗| 吕梁市| 德惠市| 闽清县| 哈尔滨市| 中方县| 陆河县| 绥阳县| 马关县| 罗田县| 扎囊县| 西峡县| 永康市| 馆陶县| 阳信县| 黄浦区| 江达县| 石首市| 景洪市| 杭锦旗| 梁山县| 阜康市| 综艺| 安乡县| 松桃| 卢龙县| 磐石市|