亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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)境我就不必多說(shuō)了,如果你不想用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的操作就好了,因此不過(guò)多贅述

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中拿出來(lái)到cpu,不然會(huì)報(bào)錯(cuò)。
    print(f"cost :{time() - start_time}s")

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

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

具體步驟:

  • 導(dǎo)入兩個(gè)庫(kù)文件,librosa和音頻文件讀寫(xiě)庫(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)行文件寫(xiě)入
    print(f"cost :{time() - start_time}s")

總結(jié):

  • 優(yōu)點(diǎn),簡(jiǎn)單小巧,ibrosa有很多能處理音頻的功能
  • 缺點(diǎn):無(wú)法調(diào)用cuda,保存的時(shí)候需要依賴(lài)soundfile庫(kù)。
  • 時(shí)間:也是幾秒左右,和torchaudiocpu版差不多
  • 小聲bb:提取32k的效果好像沒(méi)有torchaudio好【嘛,畢竟librosa歷史有點(diǎn)久了,沒(méi)有專(zhuā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)行文件寫(xiě)入
    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

讓我們來(lái)看看它官方的example,仿照著來(lái)寫(xiě)就好啦

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

步驟:

  • 導(dǎo)入依賴(lài)
import torchaudio
import torchaudio.transforms as Tf
import matplotlib.pyplot as plt     #畫(huà)圖依賴(lài)
  • 導(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)
    # 繪制基頻特征 這部分可以忽略,只是畫(huà)圖而已,可以直接復(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)見(jiàn)官方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),不過(guò)多了兩個(gè)參數(shù) voiced_flag, voiced_probs,看起來(lái)的視覺(jué)圖好像也有些不一樣,不過(guò)都是按照官方的這個(gè)來(lái)了,這也不對(duì)的話(huà)我也不會(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特征見(jiàn)下一章 

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

相關(guān)文章

  • python讀取各種文件數(shù)據(jù)方法解析

    python讀取各種文件數(shù)據(jù)方法解析

    這篇文章主要為大家詳細(xì)介紹了python讀取各種文件數(shù)據(jù)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-12-12
  • python利用Opencv實(shí)現(xiàn)人臉識(shí)別功能

    python利用Opencv實(shí)現(xiàn)人臉識(shí)別功能

    這篇文章主要為大家詳細(xì)介紹了python利用Opencv實(shí)現(xiàn)人臉識(shí)別功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-04-04
  • python定間隔取點(diǎn)(np.linspace)的實(shí)現(xiàn)

    python定間隔取點(diǎn)(np.linspace)的實(shí)現(xiàn)

    今天小編就為大家分享一篇python定間隔取點(diǎn)(np.linspace)的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-11-11
  • Python拼接字符串的7種方法總結(jié)

    Python拼接字符串的7種方法總結(jié)

    這篇文章主要給大家總結(jié)介紹了關(guān)于Python拼接字符串的7種方法,分別是來(lái)自C語(yǔ)言的%方式、format()拼接方式、() 類(lèi)似元組方式、面向?qū)ο竽0迤唇印oin()拼接方式以及f-string方式,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2018-11-11
  • python實(shí)現(xiàn)會(huì)員信息管理系統(tǒng)(List)

    python實(shí)現(xiàn)會(huì)員信息管理系統(tǒng)(List)

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)會(huì)員信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • 使用tensorflow實(shí)現(xiàn)AlexNet

    使用tensorflow實(shí)現(xiàn)AlexNet

    這篇文章主要為大家詳細(xì)介紹了使用tensorflow實(shí)現(xiàn)AlexNet,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • Pandas讀取行列數(shù)據(jù)最全方法

    Pandas讀取行列數(shù)據(jù)最全方法

    本文主要介紹了Pandas讀取行列數(shù)據(jù)最全方法,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • 從運(yùn)行效率與開(kāi)發(fā)效率比較Python和C++

    從運(yùn)行效率與開(kāi)發(fā)效率比較Python和C++

    今天小編就為大家分享一篇關(guān)于從運(yùn)行效率與開(kāi)發(fā)效率比較Python和C++,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2018-12-12
  • python enumerate內(nèi)置函數(shù)用法總結(jié)

    python enumerate內(nèi)置函數(shù)用法總結(jié)

    這篇文章主要介紹了python enumerate內(nèi)置函數(shù)用法總結(jié),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-01-01
  • Python計(jì)算標(biāo)準(zhǔn)差之numpy.std和torch.std的區(qū)別

    Python計(jì)算標(biāo)準(zhǔn)差之numpy.std和torch.std的區(qū)別

    Torch自稱(chēng)為神經(jīng)網(wǎng)絡(luò)中的numpy,它會(huì)將torch產(chǎn)生的tensor放在GPU中加速運(yùn)算,就像numpy會(huì)把a(bǔ)rray放在CPU中加速運(yùn)算,下面這篇文章主要給大家介紹了關(guān)于Python?Numpy計(jì)算標(biāo)準(zhǔn)差之numpy.std和torch.std區(qū)別的相關(guān)資料,需要的朋友可以參考下
    2022-08-08

最新評(píng)論