Voice recording using Flutter
Asked Answered
T

4

8

I am trying to build an app using Flutter which will have voice recorder in it. How do I access voice recorder? Please help me figure out the Packages, Dependencies and Code for it.

Theme answered 20/10, 2019 at 9:24 Comment(0)
W
5

You can use the audio_recorder package:

https://pub.dev/packages/audio_recorder

// Import package
import 'package:audio_recorder/audio_recorder.dart';

// Check permissions before starting
bool hasPermissions = await AudioRecorder.hasPermissions;

// Get the state of the recorder
bool isRecording = await AudioRecorder.isRecording;

// Start recording
await AudioRecorder.start(path: _controller.text, audioOutputFormat: AudioOutputFormat.AAC);

// Stop recording
Recording recording = await AudioRecorder.stop();
print("Path : ${recording.path},  Format : ${recording.audioOutputFormat},  Duration : ${recording.duration},  Extension : ${recording.extension},");
Wordage answered 20/10, 2019 at 13:30 Comment(0)
S
3

Another valid approach is to use https://pub.dev/packages/flutter_sound package.

Usage example from docs:

Future<String> result = await flutterSound.startRecorder(codec: t_CODEC.CODEC_AAC,);

result.then(path) {
    print('startRecorder: $path');

    _recorderSubscription = flutterSound.onRecorderStateChanged.listen((e) {
    DateTime date = new DateTime.fromMillisecondsSinceEpoch(e.currentPosition.toInt());
    String txt = DateFormat('mm:ss:SS', 'en_US').format(date);
    });
}

Apparently, only AAC codec is valid choice for the recording for now. At least, other options didn't work for me.

Sonia answered 21/3, 2020 at 15:31 Comment(0)
K
1

This is my code it is same way Whatsapp recordings work. when you long press on mic icon start recording and the icon able to drag to another icon like delete. I have used "path_provider" , "record", and "audioplayers" libraries.

       Material(
        child: Container(
          padding: EdgeInsets.only(top: 0, bottom: 12, left: 5, right: 5),
          child: LongPressDraggable(
            child: Icon(
              Icons.mic,
              color: Colors.black54,
            ),
            onDragStarted: () async {
              stopWatchTimer.onExecute.add(StopWatchExecute.reset);
              stopWatchTimer.onExecute.add(StopWatchExecute.start);
              seconds = 0;
              minutes = 0;
              setState(() {
                showMic = true;
              });
              isRecording = true;
              bool result = await Record().hasPermission();
              if (result) {
                Directory tempDir = await getTemporaryDirectory();
                File filePath = File('${tempDir.path}/audio.mp3');
                audioPath = filePath.path;
                await Record().start(
                  path: filePath.path, // required
                  encoder: AudioEncoder.AAC, // by default
                  bitRate: 128000, // by default
                  samplingRate: 44100, // by default
                );
              }
            },
            onDragEnd: (a) async {
              if(a.offset.dx<width-width/5){
                  await Record().stop();
                  AudioPlayer audioPlayer = AudioPlayer(
                    mode: PlayerMode.MEDIA_PLAYER,
                  );
                  int result = await audioPlayer.play(audioPath,
                      isLocal: true, stayAwake: true);
                  stopWatchTimer.onExecute.add(StopWatchExecute.stop);
                  setState(() {
                    showMic = false;
                    isRecording = false;
                  });

              }else{
                setState(() {
                  showMic = false;
                  isRecording = false;
                });
                StaticDataAndFunctions.customToastMessage(
                    "Record removed!");
              }

            },
            feedback: Icon(
              Icons.delete,
              color: Colors.black54,
            ),
          ),
        ),
        color: Colors.white,
      ),
Knipe answered 19/2, 2022 at 12:30 Comment(0)
D
0

Voice recording in flutter can be done using various packages, but I suggest record package

It is easy if you follow the following steps:

Step 1: Declare variable for storing audio recording data:

  int recordDuration = 0;
  Timer? _timer;
  final _audioRecorder = Record();
  StreamSubscription<RecordState>? _recordSub;
  RecordState recordState = RecordState.stop;
  String? audioPath;
  bool? isRecording;
  String? minutes = "00";
  String? seconds = "00";

Step 2: Create initiate method:

initRecorder() async {
    _recordSub = _audioRecorder.onStateChanged().listen((recordStateThis) {
      recordState = recordStateThis;
    });
    audioPath = null;
    isRecorderInitialized = true;
  }

Step 3: Create methods for starting, stopping, resuming, pausing recording:

Future<void> _start() async {
    try {
      if (await _audioRecorder.hasPermission()) {
        final isSupported = await _audioRecorder.isEncoderSupported(
          AudioEncoder.aacLc,
        );
        if (kDebugMode) {
          print('${AudioEncoder.aacLc.name} supported: $isSupported');
        }
        // isRecording = await _audioRecorder.isRecording();
        await _audioRecorder.start();
        recordDuration = 0;
        _startTimer();
      }
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

  Future<void> _stop() async {
    _timer?.cancel();
    recordDuration = 0;
    final path = await _audioRecorder.stop();
    if (path != null) {
      onStop(path);
    }
  }


  Future<void> _pause() async {
    _timer?.cancel();
    await _audioRecorder.pause();
  }

  Future<void> _resume() async {
    _startTimer();
    await _audioRecorder.resume();
  }

Step 4: Declare method for starting timer:

void _startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      recordDuration++;
      minutes = _formatNumber(recordDuration ~/ 60);
      seconds = _formatNumber(recordDuration % 60);
    });
  }

  String _formatNumber(int number) {
    String numberStr = number.toString();
    if (number < 10) {
      numberStr = '0$numberStr';
    }

    return numberStr;
  }

Step 5: Dispose recorder at end:

disposeRecorder() {
    _timer?.cancel();
    _recordSub?.cancel();
    _audioRecorder.dispose();
    isRecorderInitialized = false;
    debugPrint("Dispose Success");
  }

Step 6: Use these methods in your ui.

Differentiable answered 13/10, 2023 at 5:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.