音频变速python版

ops/2024/10/21 10:09:02/

音频变速

如何能在不改变音频其他特点的情况下,只改变语速呢?
有几个python的库可以实现该功能,下面一一介绍。

pydub库

首先,确保安装了pydub和ffmpeg
下面是一个简单的Python脚本,展示如何改变音频的播放速度:

python">from pydub import AudioSegment
from pydub.playback import playdef change_speed(audio_file, speed=1.0):sound = AudioSegment.from_file(audio_file)# 增加速度sound_with_altered_speed = sound._spawn(sound.raw_data, overrides={"frame_rate": int(sound.frame_rate * speed)}).set_frame_rate(sound.frame_rate)return sound_with_altered_speed# 加载音频文件
audio_path = "your_audio_file.mp3"
# 改变速度,例如1.5倍速
altered_sound = change_speed(audio_path, speed=1.5)
# 播放修改后的音频
play(altered_sound)
# 导出音频
altered_sound.export("modified_audio.mp3", format="mp3")

change_speed函数接受原始音频文件路径和速度因子。通过修改帧率来改变速度。如果你想要加快速度,可以将速度因子设置为大于1的值;如果想要减慢速度,将其设置为小于1的值。

但是该方法在改变语音的同时,使得音调也发生改变。

librosa库

librosa主要用于音乐和音频分析。它支持音频的时间伸缩(即改变音频速度而不改变音调),并且提供了许多其他音频处理功能。

实现代码:

python">import librosa
import soundfile as sfaudio_path = 'your_audio_file.wav'
y, sr = librosa.load(audio_path, sr=None)  # sr=None 保持原始采样率# 变速处理,比如加速1.5倍
y_change = librosa.effects.time_stretch(y, 1.5)
#保存
sf.write('output_audio_file.wav', y_change, sr)

在改变音频速度的同时保持原有音调,librosa使用了时间拉伸算法(Time Stretching)。
librosa.effects.time_stretch函数是用于调整音频的播放速度,同时不改变音频的音高(音调)。
我们看下这个函数源码:

python">def time_stretch(y, rate, **kwargs):'''Time-stretch an audio series by a fixed rate.'''if rate <= 0:raise ParameterError('rate must be a positive number')# Construct the short-term Fourier transform (STFT)stft = core.stft(y, **kwargs)# Stretch by phase vocodingstft_stretch = core.phase_vocoder(stft, rate)# Predict the length of y_stretchlen_stretch = int(round(len(y)/rate))# Invert the STFTy_stretch = core.istft(stft_stretch, dtype=y.dtype, length=len_stretch, **kwargs)return y_stretch

可以看到,该函数主要包含三个步骤:
1.音频的频谱表示
首先,librosa.effects.time_stretch利用短时傅里叶变换(STFT)将音频信号从时间域转换到频域。这种转换将音频分解成其组成的频率成分,每个成分都有相应的幅度和相位。

2.相位估计(phase_vocoder)
在进行时间伸缩处理时,保持相位连续性是一个重要的挑战。librosa采用了相位估计技术来调整每个频率成分的相位,以保证在变速过程中音频信号的相位连续性。这是通过相位重构实现的,确保在变速后的音频中,所有频率成分的相位都能正确对齐。

3.相位恢复和重构,重建音频
处理相位信息时,使用相位展开技术,从原始音频中提取和修改相位信息,然后在处理过程中适当调整这些信息以匹配新的时间伸缩率。
最后,将处理过的频谱数据通过逆短时傅里叶变换(ISTFT)重新转换回时间域,生成最终的音频输出。在这一步中,经过调整的幅度和重构的相位信息被合成,以产生时间伸缩后的音频信号。

补充:相位声码器Phase vocoder
相位声码器(phase vocoder)是一种特殊的声码器,用于分析和修改音频信号的频谱相位。它是在数字信号处理中广泛使用的一种工具,特别适用于时间伸缩(改变音频速度而不改变音调)和音高移动(改变音调而不改变速度)。

相位声码器技术可以实现音频的时间伸缩。这一技术是基于频域处理,它可以调整音频的时长而不改变音高,主要依靠精确的相位处理。

先看看源码:

python">def phase_vocoder(D, rate, hop_length=None):"""Phase vocoder.  Given an STFT matrix D, speed up by a factor of `rate`Based on the implementation provided by [1]_... note:: This is a simplified implementation, intended primarily forreference and pedagogical purposes.  It makes no attempt tohandle transients, and is likely to produce many audibleartifacts.  For a higher quality implementation, we recommendthe RubberBand library [2]_ and its Python wrapper `pyrubberband`... [1] Ellis, D. P. W. "A phase vocoder in Matlab."Columbia University, 2002.http://www.ee.columbia.edu/~dpwe/resources/matlab/pvoc/.. [2] https://breakfastquay.com/rubberband/Parameters----------D : np.ndarray [shape=(d, t), dtype=complex]STFT matrixrate :  float > 0 [scalar]Speed-up factor: `rate > 1` is faster, `rate < 1` is slower.hop_length : int > 0 [scalar] or NoneThe number of samples between successive columns of `D`.If None, defaults to `n_fft/4 = (D.shape[0]-1)/2`Returns-------D_stretched : np.ndarray [shape=(d, t / rate), dtype=complex]time-stretched STFTSee Also--------pyrubberband"""n_fft = 2 * (D.shape[0] - 1)if hop_length is None:hop_length = int(n_fft // 4)time_steps = np.arange(0, D.shape[1], rate, dtype=np.float)# Create an empty output arrayd_stretch = np.zeros((D.shape[0], len(time_steps)), D.dtype, order='F')# Expected phase advance in each binphi_advance = np.linspace(0, np.pi * hop_length, D.shape[0])# Phase accumulator; initialize to the first samplephase_acc = np.angle(D[:, 0])# Pad 0 columns to simplify boundary logicD = np.pad(D, [(0, 0), (0, 2)], mode='constant')for (t, step) in enumerate(time_steps):columns = D[:, int(step):int(step + 2)]# Weighting for linear magnitude interpolationalpha = np.mod(step, 1.0)mag = ((1.0 - alpha) * np.abs(columns[:, 0])+ alpha * np.abs(columns[:, 1]))# Store to output arrayd_stretch[:, t] = mag * np.exp(1.j * phase_acc)# Compute phase advancedphase = (np.angle(columns[:, 1])- np.angle(columns[:, 0])- phi_advance)# Wrap to -pi:pi rangedphase = dphase - 2.0 * np.pi * np.round(dphase / (2.0 * np.pi))# Accumulate phasephase_acc += phi_advance + dphasereturn d_stretch

直接调用调用phase_vocoder来实现时间伸缩。这里是一个简单的示例:

python">import librosa# 加载音频数据
y, sr = librosa.load('audio_file.wav', sr=None)# 计算STFT
D = librosa.stft(y)# 应用相位声码器进行时间伸缩
D_stretched = librosa.core.phase_vocoder(D, rate=1.5)# 通过逆STFT重构音频
y_stretched = librosa.istft(D_stretched)

基本原理:
在这里插入图片描述


http://www.ppmy.cn/ops/7526.html

相关文章

Golang | Leetcode Golang题解之第36题有效的数独

题目&#xff1a; 题解&#xff1a; func isValidSudoku(board [][]byte) bool {var rows, columns [9][9]intvar subboxes [3][3][9]intfor i, row : range board {for j, c : range row {if c . {continue}index : c - 1rows[i][index]columns[j][index]subboxes[i/3][j/3]…

抓取电商产品数据的方法|电商平台商品详情数据|批量上架|商品搬家|电商封装API数据采集接口更高效安全的数据采集

大量级电商数据采集时使用电商API接口有以下优势&#xff1a; 1. 数据准确性&#xff1a;通过电商API接口获取数据&#xff0c;可以保证数据的准确性和实时性&#xff0c;避免了手动采集可能出现的错误和延迟。 2. 自动化采集&#xff1a;API接口可以实现自动化的数据获取和更…

zabbix 自动发现与自动注册 部署 zabbix 代理服务器

zabbix 自动发现&#xff08;对于 agent2 是被动模式&#xff09; zabbix server 主动的去发现所有的客户端&#xff0c;然后将客户端的信息登记在服务端上。 缺点是如果定义的网段中的主机数量多&#xff0c;zabbix server 登记耗时较久&#xff0c;且压力会较大。1.确保客户端…

java-单列集合List详解

一、List概述 ​​​​​​​List 接口继承自 Collection 接口。这意味着所有 List 类型的对象都是 Collection 类型的对象&#xff0c;它们共享 Collection 接口中定义的所有方法。 List集合的特点&#xff1a; 1、有序&#xff1a;存和取得元素顺序一致 2、有索引&#xf…

[git] 使用git和github工作思路和经验

上传到github之前&#xff0c;在本地把commit整理好 有时候在本地修改代码时&#xff0c;会涉及到一些拼写错误和编译错误&#xff0c;这个过程可能反复操作很久&#xff0c;因此会产生很多意义不大的commit&#xff0c;如果不对这些commit进行合并就直接上传到github上对应的…

公园高速公路景区校园IP网络广播音柱SIP音柱

公园高速公路景区校园IP网络广播音柱SIP音柱 适用于学校、车站、教堂、工厂、仓库、公园停车场及露天市场高速公路等场所播放录制语音文件或背景音乐节目&#xff0c;专业一体化音箱设计&#xff0c;高强度防水设计&#xff0c;符合IP54防护等认证&#xff0c;数字化产品&…

【Python基础】MySQL

文章目录 [toc]创建数据库创建数据表数据插入数据查询数据更新 个人主页&#xff1a;丷从心 系列专栏&#xff1a;Python基础 学习指南&#xff1a;Python学习指南 创建数据库 import pymysqldef create_database():db pymysql.connect(hostlocalhost, userroot, passwordr…

基于单片机和安卓平台的移动物联网应用开发实训系统设计

摘要:文章介绍了一种采用单片机和安卓移动设备构建移动物联网应用开发实训系统的方法。并基于该系统完成了实训的项目设计,实现了通过手机远程获取单片机上的传感器数据以及远程控制单片机上的开关设备等典型的物联网应用。 关键词:单片机;传感器;安卓应用开发 1 物联网应…