Flutter音频录制插件record_mp3的使用

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

Flutter音频录制插件record_mp3的使用

简介

Record Mp3 是一个用于Flutter应用程序中进行MP3格式音频录制的插件。它利用平台原生API实现录音功能,支持iOS和Android平台。

依赖配置

根据您的Flutter版本,在pubspec.yaml文件中添加如下依赖:

  • 对于 Flutter <= 1.19.x:
dependencies:
  record_mp3: ^1.0.1
  • 对于 Flutter >=1.12.x <2.0.0:
dependencies:
  record_mp3: ^2.1.0
  • 对于 Flutter >=2.0.0 (Null Safety):
dependencies:
  record_mp3: ^3.0.0

或者从GitHub直接引用最新版:

dependencies:
  record_mp3: 
  	git:
	 url: git://github.com/fluttercandies/flutter_record_mp3

使用方法

iOS 特别注意

确保在Info.plist文件中添加麦克风权限描述:

<key>NSMicrophoneUsageDescription</key>
<string>需要您的同意来访问麦克风</string>

示例代码

下面是一个完整的示例demo,展示了如何使用record_mp3插件创建一个简单的录音应用,包括开始、暂停、继续和停止录音的功能,并且可以播放录制完成的音频文件。

main.dart

import 'dart:io';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
import 'package:record_mp3/record_mp3.dart';
import 'package:permission_handler/permission_handler.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String statusText = "";
  bool isComplete = false;
  String recordFilePath;

  Future<bool> checkPermission() async {
    if (!await Permission.microphone.isGranted) {
      PermissionStatus status = await Permission.microphone.request();
      if (status != PermissionStatus.granted) {
        return false;
      }
    }
    return true;
  }

  void startRecord() async {
    bool hasPermission = await checkPermission();
    if (hasPermission) {
      statusText = "Recording...";
      recordFilePath = await getFilePath();
      isComplete = false;
      RecordMp3.instance.start(recordFilePath, (type) {
        statusText = "Record error--->$type";
        setState(() {});
      });
    } else {
      statusText = "No microphone permission";
    }
    setState(() {});
  }

  void pauseRecord() {
    if (RecordMp3.instance.status == RecordStatus.PAUSE) {
      bool s = RecordMp3.instance.resume();
      if (s) {
        statusText = "Recording...";
        setState(() {});
      }
    } else {
      bool s = RecordMp3.instance.pause();
      if (s) {
        statusText = "Recording pause...";
        setState(() {});
      }
    }
  }

  void stopRecord() {
    bool s = RecordMp3.instance.stop();
    if (s) {
      statusText = "Record complete";
      isComplete = true;
      setState(() {});
    }
  }

  void play() {
    if (recordFilePath != null && File(recordFilePath).existsSync()) {
      AudioPlayer audioPlayer = AudioPlayer();
      audioPlayer.play(recordFilePath, isLocal: true);
    }
  }

  int i = 0;

  Future<String> getFilePath() async {
    Directory storageDirectory = await getApplicationDocumentsDirectory();
    String sdPath = "${storageDirectory.path}/record";
    var d = Directory(sdPath);
    if (!d.existsSync()) {
      d.createSync(recursive: true);
    }
    return "$sdPath/test_${i++}.mp3";
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                child: GestureDetector(
                  child: Container(
                    height: 48.0,
                    decoration: BoxDecoration(color: Colors.red.shade300),
                    child: Center(
                      child: Text(
                        'start',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  onTap: () async {
                    startRecord();
                  },
                ),
              ),
              Expanded(
                child: GestureDetector(
                  child: Container(
                    height: 48.0,
                    decoration: BoxDecoration(color: Colors.blue.shade300),
                    child: Center(
                      child: Text(
                        RecordMp3.instance.status == RecordStatus.PAUSE
                            ? 'resume'
                            : 'pause',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  onTap: () {
                    pauseRecord();
                  },
                ),
              ),
              Expanded(
                child: GestureDetector(
                  child: Container(
                    height: 48.0,
                    decoration: BoxDecoration(color: Colors.green.shade300),
                    child: Center(
                      child: Text(
                        'stop',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  onTap: () {
                    stopRecord();
                  },
                ),
              ),
            ],
          ),
          Padding(
            padding: const EdgeInsets.only(top: 20.0),
            child: Text(
              statusText,
              style: TextStyle(color: Colors.red, fontSize: 20),
            ),
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              play();
            },
            child: Container(
              margin: EdgeInsets.only(top: 30),
              alignment: AlignmentDirectional.center,
              width: 100,
              height: 50,
              child: isComplete && recordFilePath != null
                  ? Text(
                      "play",
                      style: TextStyle(color: Colors.red, fontSize: 20),
                    )
                  : Container(),
            ),
          ),
        ]),
      ),
    );
  }
}

此示例提供了一个基础框架,您可以根据实际需求对其进行扩展或修改。希望这能帮助您快速上手使用record_mp3插件!如果有任何问题,欢迎随时提问。


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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用record_mp3插件进行音频录制的代码示例。这个插件允许你以MP3格式录制音频。

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

dependencies:
  flutter:
    sdk: flutter
  record_mp3: ^x.y.z  # 请替换为最新版本号

然后,运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤实现音频录制功能:

  1. 导入必要的包
import 'package:flutter/material.dart';
import 'package:record_mp3/record_mp3.dart';
import 'dart:io';
  1. 创建一个用于录制音频的页面
class AudioRecorderPage extends StatefulWidget {
  @override
  _AudioRecorderPageState createState() => _AudioRecorderPageState();
}

class _AudioRecorderPageState extends State<AudioRecorderPage> {
  RecordMp3? _recorder;
  String _path = "";
  bool _isRecording = false;

  @override
  void initState() {
    super.initState();
    _initRecorder();
  }

  Future<void> _initRecorder() async {
    _recorder = RecordMp3(
      path: _getLocalPath('audio_record.mp3'),
      encoder: AudioEncoder.mp3,
      bitRate: 128000,
    );
  }

  Future<String> _getLocalPath(String fileName) async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path + '/' + fileName;
  }

  void _startRecording() async {
    if (!_isRecording) {
      setState(() {
        _isRecording = true;
      });
      await _recorder!.start();
    }
  }

  void _stopRecording() async {
    if (_isRecording) {
      await _recorder!.stop();
      setState(() {
        _isRecording = false;
        _path = _recorder!.path!;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Audio Recorder'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: _isRecording ? _stopRecording : _startRecording,
              child: Text(_isRecording ? 'Stop' : 'Start'),
            ),
            SizedBox(height: 20),
            if (_path.isNotEmpty)
              ElevatedButton(
                onPressed: () async {
                  final result = await showDialog(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                        title: Text('Share Audio'),
                        content: Text('Audio saved at $_path'),
                        actions: <Widget>[
                          TextButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                            child: Text('Cancel'),
                          ),
                          TextButton(
                            onPressed: () async {
                              final File file = File(_path);
                              if (await canLaunch(file.path)) {
                                await launch(file.path);
                              } else {
                                throw 'Could not launch file';
                              }
                              Navigator.of(context).pop();
                            },
                            child: Text('Open'),
                          ),
                        ],
                      );
                    },
                  );
                },
                child: Text('Share'),
              ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _recorder?.dispose();
    super.dispose();
  }
}
  1. main.dart中使用这个页面
import 'package:flutter/material.dart';
import 'audio_recorder_page.dart'; // 假设你将上面的代码保存为audio_recorder_page.dart

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Audio Recorder Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AudioRecorderPage(),
    );
  }
}

这个示例展示了如何使用record_mp3插件来录制音频,并在录制完成后提供一个按钮来分享或打开录制的音频文件。请注意,分享功能使用了url_launcher包来打开文件路径(在实际应用中,你可能需要更复杂的分享逻辑)。你可以根据需要添加url_launcher依赖并实现更复杂的分享功能。

希望这个示例对你有所帮助!

回到顶部