You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何调整语音音调并实现各类变声效果?

Flutter变声应用:实现男声/女声等音效切换

你已经用Flutter Sounds搞定了录制和播放,接下来的变声核心是修改音频的音调、语速参数,结合音频处理工具就能实现。以下是具体步骤:

1. 引入音频处理依赖

Flutter Sounds本身不提供音频效果处理,我们用flutter_ffmpeg来实现音频转码和效果调整,在pubspec.yaml中添加:

dependencies:
  flutter_sounds: ^3.1.0 # 替换成你当前使用的版本
  flutter_ffmpeg: ^0.4.0

执行flutter pub get安装依赖。

2. 确保录制的音频已保存到本地

在你的录制逻辑中,确保录制完成后拿到原始音频的本地文件路径:

// 假设你已经初始化了FlutterSoundsRecorder实例
String? recordedFilePath = await _recorder.stopRecorder();
if (recordedFilePath == null) {
  // 处理录制失败的情况
  return;
}

3. 实现不同变声效果的处理函数

变声的关键是通过FFmpeg滤镜调整音频的采样率(改变音调)和语速(补偿时长),同时添加降噪提升音质:

import 'package:flutter_ffmpeg/flutter_ffmpeg.dart';

final _ffmpeg = FlutterFFmpeg();

// 女声效果:提高音调(采样率提升20%),保持语速不变
Future<String> applyFemaleEffect(String inputPath) async {
  final outputPath = "${inputPath}_female.mp3";
  // afftdn降噪,asetrate调整采样率改音调,atempo补偿语速
  final command = "-i $inputPath -filter_complex \"afftdn=nf=-20, asetrate=44100*1.2, atempo=1/1.2\" $outputPath";
  await _ffmpeg.execute(command);
  return outputPath;
}

// 男声效果:降低音调(采样率降低20%)
Future<String> applyMaleEffect(String inputPath) async {
  final outputPath = "${inputPath}_male.mp3";
  final command = "-i $inputPath -filter_complex \"afftdn=nf=-20, asetrate=44100*0.8, atempo=1/0.8\" $outputPath";
  await _ffmpeg.execute(command);
  return outputPath;
}

// 卡通音:更高音调+稍快语速
Future<String> applyCartoonEffect(String inputPath) async {
  final outputPath = "${inputPath}_cartoon.mp3";
  final command = "-i $inputPath -filter_complex \"afftdn=nf=-20, asetrate=44100*1.5, atempo=1.2\" $outputPath";
  await _ffmpeg.execute(command);
  return outputPath;
}

4. 绑定按钮点击事件,切换音效并播放

在UI中添加对应按钮,点击后调用处理函数,然后用Flutter Sounds播放处理后的音频:

String? _currentPlayPath;

// 女声按钮点击逻辑
void onFemaleBtnPressed() async {
  if (recordedFilePath == null) return;
  _currentPlayPath = await applyFemaleEffect(recordedFilePath!);
  // 停止当前播放(如果有的话),再播放变声后的音频
  await _player.stopPlayer();
  await _player.startPlayer(fromURI: _currentPlayPath!);
}

// 男声按钮点击逻辑
void onMaleBtnPressed() async {
  if (recordedFilePath == null) return;
  _currentPlayPath = await applyMaleEffect(recordedFilePath!);
  await _player.stopPlayer();
  await _player.startPlayer(fromURI: _currentPlayPath!);
}

5. 优化提示

  • 实时变声:如果需要边录边变声,你需要监听Flutter Sounds的音频流回调,实时处理每帧音频数据后再播放,这需要更底层的音频处理(比如借助Native插件或audio_engine库),复杂度较高,建议先完成录制后变声的方案。
  • 缓存优化:对同一原始音频和同一音效的处理结果做缓存,避免重复执行FFmpeg命令浪费资源。
  • 错误处理:给FFmpeg执行添加错误监听,处理转码失败的情况:
final rc = await _ffmpeg.execute(command);
if (rc != 0) {
  print("音效处理失败,FFmpeg返回码:$rc");
  // 这里可以给用户弹出提示
}
  • 权限检查:确保已经申请了存储读写权限,否则无法保存处理后的音频文件。

内容的提问来源于stack exchange,提问作者Ahmad Amini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 08:12:51