how to automatically trigger record

Viewed 14

I have a audio recording page which starts when I tap in the button and stop when i tap the button once again

import 'package:flutter_sound/flutter_sound.dart'; import 'package:permission_handler/permission_handler.dart';

    class AudioWidget extends StatefulWidget {
  @override
  State<AudioWidget> createState() => _AudioWidgetState();
}

``class _AudioWidgetState extends State<AudioWidget> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  String AudioUrl = '';
  final recorder = FlutterSoundRecorder();
  bool isRecorderReady = false;

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

    initRecorder();
    record();
  }

  @override
  void dispose() {
    recorder.closeRecorder();

    super.dispose();
  }

  Future initRecorder() async {
    final status = await Permission.microphone.request();
    if (status != PermissionStatus.granted) {
      throw 'Microphone permission not granted';
    }
    await recorder.openRecorder();
    isRecorderReady = true;
    recorder.setSubscriptionDuration(const Duration(milliseconds: 500));
  }

  Future record() async {
    if (!isRecorderReady) {
      return;
    }
    await recorder.startRecorder(toFile: 'audio');
  }

  Future stop() async {
    if (!isRecorderReady) {
      return;
    }
    final path = await recorder.stopRecorder();
    final audioFile = File(path!);
    print('Recorder audio: $audioFile');

    final ref = FirebaseStorage.instance
        .ref()
        .child('Audio')
        .child(DateTime.now().toIso8601String() + ".mp3");
    await ref.putData(audioFile.readAsBytesSync());
    AudioUrl = await ref.getDownloadURL();
    FirebaseFirestore.instance.collection('Audio').add({
      'AudioUrl': AudioUrl,
      'userId': _auth.currentUser!.email,
      'createdAt': DateTime.now(),
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Audio"),
        ),
        body: Center(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            StreamBuilder<RecordingDisposition>(
                stream: recorder.onProgress,
                builder: (context, snapshot) {
                  final duration = snapshot.hasData
                      ? snapshot.data!.duration
                      : Duration.zero;
                  String twoDigits(int n) => n.toString().padLeft(2, '0');
                  final twoDigitMinutes =
                      twoDigits(duration.inMinutes.remainder(60));
                  final twoDigitSeconds =
                      twoDigits(duration.inSeconds.remainder(60));
                  if (twoDigitSeconds ==
                      FFAppState().AudioMaxDuration.toString()) {
                    stop();
                  }

                  return Text('$twoDigitMinutes:$twoDigitSeconds',
                      style: const TextStyle(
                        fontSize: 80,
                        fontWeight: FontWeight.bold,
                      ));
                }),
            const SizedBox(height: 32),
            ElevatedButton(
              child: Icon(
                recorder.isRecording ? Icons.stop : Icons.mic,
                size: 80,
              ),
              onPressed: () async {
                if (recorder.isRecording) {
                  await stop();
                  context.pop();
                } else {
                  await record();
                }
                setState(() {});
              },
            ),
          ],
        )),
      ),
    );
  }
}

how can I automatically start recording once I open the audio recording page and tap it to stop and tap again to start?

I tried to put the record function in initstate but it didn't work

void initState() {
     super.initState(); 
     initRecorder(); 
     record(); 
        }
0 Answers
Related