使用librosa對音訊進行載入拼接擷取疊加等操作
阿新 • • 發佈:2020-12-11
注意:librosa只能讀取wav格式音訊檔案
程式碼如下
import numpy as np
import librosa
# 1.載入音訊檔案
audio_path1 = './audio1.wav'
y1, sr1 = librosa.load(audio_path1)
dur1 = librosa.get_duration(y1, sr=sr1)
print('資料x型別和取樣率sr型別', type(y1), type(sr1))
print('資料x尺寸和取樣率', y1.shape, sr1)
print('該音訊的時長為:', dur1)
audio_path2 = './audio2.wav'
y2, sr2 = librosa.load(audio_path2)
dur2 = librosa.get_duration(y2, sr=sr2)
print('資料x型別和取樣率sr型別', type(y2), type(sr2))
print('資料x尺寸和取樣率', y2.shape, sr2)
print('該音訊的時長為:', dur2)
# 2.音訊拼接
audio_dst = np.hstack((y1, y2))
print('資料x尺寸和取樣率', audio_dst.shape)
librosa.output. write_wav('./拼接.wav', audio_dst, sr2)
# 3.音訊擷取
start = 12
duration = 20
stop = start +duration
audio_dst = y2[start*sr2:stop*sr2]
librosa.output.write_wav('./擷取-2.wav', audio_dst, sr2)
# 4.音訊疊加
num_min = min(len(y1), len(y2))
num_max = max(len(y1), len(y2))
audio_dst = np.zeros(num_max)
for i in range (num_max):
if i<num_min:
audio_dst[i] = y1[i] + y2[i]
else:
if len(y1)>=len(y2):
audio_dst[i] = y1[i]
else:
audio_dst[i] = y2[i]
librosa.output.write_wav('./疊加.wav', audio_dst, sr2)
# 5.生成靜音音訊
num = 3*sr2
audio_dst = np.zeros(num)
librosa.output.write_wav('./靜音.wav', audio_dst, sr2)
# 6.調整音訊音量
librosa.output.write_wav('./調整音量.wav', y2*0.1, sr2)