Flutter音频处理插件flutter_sound_suite的使用

发布于 1周前 作者 ionicwang 来自 Flutter

Flutter音频处理插件flutter_sound_suite的使用

flutter_sound_suite 是一个用于轻松记录和播放声音的 Flutter 插件!

依赖项

以下是 flutter_sound_suite 所需的依赖项:

dependencies:
  dio: ^4.0.0
  intl: ^0.17.0
  uuid: ^3.0.4
  provider: ^5.0.0
  path_provider: ^2.0.2
  flutter_sound: ^8.1.4
  permission_handler: ^8.0.1

支持的编解码器

flutter_sound 支持以下编解码器:

编码器 AAC ADS Opus OGG Opus CAF MP3 Vorbis OGG PCM raw PCM WAV PCM AIFF PCM CAF FLAC AAC MP4 AMR-NB AMR-WB
iOS 是(*)
iOS 解码器 是(*)
Android 编码器
Android 解码器 是(*) 是(*) 是(*)

(*):虽然 flutter_sound 支持这些编解码器,但需要文件格式转换。这可能会带来一些问题:

  • 需要 FFmpeg。FFmpeg 不包含在 flutter_sound 的轻量版本中。
  • 播放文件时或停止录音后可能会有一些延迟,对于非常大的录音文件,这种延迟可能相当明显。

此表格将在添加更多编解码器时进行更新。

完整示例

以下是一个完整的示例,展示了如何使用 flutter_sound_suite 进行录音和播放音频。

import 'package:flutter/material.dart';
import 'package:flutter_sound_suite/flutter_sound_suite.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(FlutterSoundSuiteApp());
}

class FlutterSoundSuiteApp extends StatefulWidget {
  @override
  _FlutterSoundSuiteAppState createState() => _FlutterSoundSuiteAppState();
}

class _FlutterSoundSuiteAppState extends State<FlutterSoundSuiteApp> {
  List<Map<String, dynamic>> data = [];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Sound Suite Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Sound Suite Demo'),
        ),
        body: ChangeNotifierProvider(
          create: (context) => SoundPlayerModel(),
          child: Container(
            child: ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                Map<String, dynamic> item = data[index];
                return Card(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(item['fileName']),
                      Text('duration ${item['duration']}'),
                      Card(
                        color: Colors.red.shade50,
                        child: SoundPlayerWidget(
                          filePath: item['filePath'],
                          fileName: item['fileName'],
                          duration: item['duration'],
                        ),
                      ),
                    ],
                  ),
                );
              },
              itemCount: data.length,
            ),
          ),
        ),
        bottomNavigationBar: SafeArea(
          child: Container(
            height: 70,
            child: SoundRecorderWidget(
              recordComplete: (
                String filePath,
                String fileName,
                double duration,
              ) {
                setState(() {
                  data.add({
                    'filePath': filePath,
                    'fileName': fileName,
                    'duration': duration,
                  });
                  debugPrint('保存到 $filePath,时长 $duration');
                });
              },
            ),
          ),
        ),
      ),
    );
  }
}

代码解释

  1. 导入必要的包

    import 'package:flutter/material.dart';
    import 'package:flutter_sound_suite/flutter_sound_suite.dart';
    import 'package:provider/provider.dart';
    
  2. 定义主应用类

    void main() {
      runApp(FlutterSoundSuiteApp());
    }
    
    class FlutterSoundSuiteApp extends StatefulWidget {
      @override
      _FlutterSoundSuiteAppState createState() => _FlutterSoundSuiteAppState();
    }
    
  3. 定义状态类

    class _FlutterSoundSuiteAppState extends State<FlutterSoundSuiteApp> {
      List<Map<String, dynamic>> data = [];
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Sound Suite Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: Scaffold(
            appBar: AppBar(
              title: Text('Flutter Sound Suite Demo'),
            ),
            body: ChangeNotifierProvider(
              create: (context) => SoundPlayerModel(),
              child: Container(
                child: ListView.builder(
                  itemBuilder: (BuildContext context, int index) {
                    Map<String, dynamic> item = data[index];
                    return Card(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(item['fileName']),
                          Text('duration ${item['duration']}'),
                          Card(
                            color: Colors.red.shade50,
                            child: SoundPlayerWidget(
                              filePath: item['filePath'],
                              fileName: item['fileName'],
                              duration: item['duration'],
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                  itemCount: data.length,
                ),
              ),
            ),
            bottomNavigationBar: SafeArea(
              child: Container(
                height: 70,
                child: SoundRecorderWidget(
                  recordComplete: (
                    String filePath,
                    String fileName,
                    double duration,
                  ) {
                    setState(() {
                      data.add({
                        'filePath': filePath,
                        'fileName': fileName,
                        'duration': duration,
                      });
                      debugPrint('保存到 $filePath,时长 $duration');
                    });
                  },
                ),
              ),
            ),
          ),
        );
      }
    }
    

更多关于Flutter音频处理插件flutter_sound_suite的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter音频处理插件flutter_sound_suite的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中处理音频,flutter_sound_suite 是一个功能强大的插件,它提供了一系列用于音频录制和播放的工具。下面是一个使用 flutter_sound_suite 的简单示例,包括如何初始化插件、录制音频以及播放音频。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 flutter_sound_suite 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_sound_suite: ^最新版本号

2. 导入包

在你的 Dart 文件中导入 flutter_sound_suite

import 'package:flutter_sound_suite/flutter_sound_suite.dart';

3. 初始化插件

State 类中初始化 FlutterSoundRecorderFlutterSoundPlayer

class _MyHomePageState extends State<MyHomePage> {
  late FlutterSoundRecorder recorder;
  late FlutterSoundPlayer player;
  late FlutterSoundRecorder? _recorderInstance;
  late FlutterSoundPlayer? _playerInstance;

  @override
  void initState() {
    super.initState();
    // 初始化Recorder
    recorder = FlutterSoundRecorder();
    recorder.openRecorder().then((value) {
      if (value == "recorder_state_ready") {
        setState(() {
          _recorderInstance = recorder;
        });
      }
    });

    // 初始化Player
    player = FlutterSoundPlayer();
    player.openPlayer().then((value) {
      if (value == "player_state_ready") {
        setState(() {
          _playerInstance = player;
        });
      }
    });
  }

  @override
  void dispose() {
    // 释放资源
    if (_recorderInstance != null) {
      _recorderInstance!.closeRecorder();
    }
    if (_playerInstance != null) {
      _playerInstance!.closePlayer();
    }
    super.dispose();
  }

4. 录制音频

添加录制音频的按钮和逻辑:

void _startRecording() async {
  if (_recorderInstance != null) {
    await _recorderInstance!.startRecorder(
      toFile: "example.wav",
      codec: Codec.pcm16,
      isStereo: true,
      sampleRate: 44100
    );
  }
}

void _stopRecording() async {
  if (_recorderInstance != null) {
    await _recorderInstance!.stopRecorder();
  }
}

5. 播放音频

添加播放音频的按钮和逻辑:

void _playAudio() async {
  if (_playerInstance != null) {
    await _playerInstance!.startPlayer(fromFile: "example.wav");
  }
}

void _stopPlaying() async {
  if (_playerInstance != null) {
    await _playerInstance!.stopPlayer();
  }
}

6. UI 布局

build 方法中创建按钮:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Flutter Sound Suite Demo'),
    ),
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ElevatedButton(
            onPressed: _startRecording,
            child: Text('Start Recording'),
          ),
          ElevatedButton(
            onPressed: _stopRecording,
            child: Text('Stop Recording'),
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: _playAudio,
            child: Text('Play Audio'),
          ),
          ElevatedButton(
            onPressed: _stopPlaying,
            child: Text('Stop Playing'),
          ),
        ],
      ),
    ),
  );
}

总结

这个示例展示了如何使用 flutter_sound_suite 插件来录制和播放音频。在实际应用中,你可能需要添加更多的错误处理和用户反馈机制。另外,flutter_sound_suite 提供了许多其他功能,如音频格式转换、音量控制等,你可以根据需求进一步探索和使用这些功能。

回到顶部