1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Flutter] Convert AAC to MP4 for use microphone

Discussão em 'Mobile' iniciado por Stack, Novembro 3, 2024 às 07:03.

  1. Stack

    Stack Membro Participativo

    I'm looking for use the microphone on flutter but I always have a crash the APP. I need it to use the microphone and send the voice to a chat.

    Please how can I do it ?

    # File on the UI

    final AudioRecorderService _audioRecorderService = AudioRecorderService();
    bool _isRecording = false;

    void _toggleRecording() async {
    if (_isRecording) {
    await _audioRecorderService.stopRecordingAndConvert();
    addDiscussionMessage(
    idDiscussion: discussionDetail['idDiscussion'],
    idType: 2,
    data: _audioRecorderService.filePath,
    ).then((_) {
    setState(() {
    futureCreateDiscussion =
    createDiscussion(name: "", idUser: widget.varToPage);
    });
    });
    print("object : ${_audioRecorderService.filePath}");
    } else {
    await _audioRecorderService.startRecording();
    }
    setState(() {
    _isRecording = !_isRecording;
    });
    }
    (...)
    IconButton(
    onPressed: _toggleRecording,
    icon: Icon(_isRecording ? Icons.mic_off : Icons.mic,
    color: ColorsDiolos.violetFonce),
    ),



    # Class to save into temp directory and convert

    import 'package:flutter/material.dart';
    import 'package:path_provider/path_provider.dart';
    import 'package:flutter_sound/flutter_sound.dart';
    import 'package:video_compress/video_compress.dart';
    import 'dart:io';

    class AudioRecorderService {
    final FlutterSoundRecorder _recorder = FlutterSoundRecorder();
    bool _isRecording = false;
    String? _filePath;

    final ValueNotifier<String?> convertedFilePathNotifier = ValueNotifier(null);

    Future<void> init() async {
    await _recorder.openRecorder();
    }

    Future<void> startRecording() async {
    if (_isRecording) return;

    try {
    Directory tempDir = await getTemporaryDirectory();
    _filePath =
    '${tempDir.path}/audio_${DateTime.now().millisecondsSinceEpoch}.aac';

    await _recorder.startRecorder(
    toFile: _filePath,
    codec: Codec.aacADTS,
    );
    _isRecording = true;
    print("Enregistrement commencé : $_filePath");
    } catch (e) {
    print("Erreur lors du démarrage de l'enregistrement : $e");
    }
    }

    Future<void> stopRecordingAndConvert() async {
    if (!_isRecording) return;

    try {
    await _recorder.stopRecorder();
    _isRecording = false;

    // Petite attente pour s'assurer que le fichier est bien créé
    await Future.delayed(Duration(milliseconds: 500));

    // Chemin de sortie pour le fichier MP4 dans le même répertoire temporaire
    Directory tempDir = await getTemporaryDirectory();
    String outputFilePath =
    '${tempDir.path}/audio_${DateTime.now().millisecondsSinceEpoch}.mp4';

    await convertAACtoMP4(_filePath!, outputFilePath);

    // Notifie l'UI avec le chemin du fichier MP4
    convertedFilePathNotifier.value = outputFilePath;
    _filePath = outputFilePath;
    print("Enregistrement arrêté et converti : $outputFilePath");
    } catch (e) {
    print("Erreur lors de l'arrêt de l'enregistrement : $e");
    }
    }

    Future<void> convertAACtoMP4(
    String inputFilePath, String outputFilePath) async {
    try {
    print("inputFile dans convert : $inputFilePath");

    // Re-vérifiez l'existence du fichier juste avant la compression
    final inputFile = File(inputFilePath);
    if (!inputFile.existsSync()) {
    print(
    "Erreur : le fichier d'entrée n'existe pas ou le chemin est incorrect.");
    return;
    }

    MediaInfo? mediaInfo = await VideoCompress.compressVideo(
    inputFilePath,
    quality: VideoQuality.DefaultQuality,
    deleteOrigin: false,
    includeAudio: true,
    );

    if (mediaInfo != null && mediaInfo.file != null) {
    File(mediaInfo.file!.path).copySync(outputFilePath);
    print('Conversion réussie : $outputFilePath');
    } else {
    print('Erreur lors de la conversion : mediaInfo est null');
    }
    } catch (e) {
    print("Exception lors de la conversion : $e");
    }
    }

    bool get isRecording => _isRecording;
    String? get filePath => _filePath;

    Future<void> dispose() async {
    await _recorder.closeRecorder();
    convertedFilePathNotifier.dispose();
    }
    }



    thank you,

    I tried with FFmpeg but I d'ont want to use it if possible

    Output from flutter : flutter: inputFile dans convert : /Users/ogosselin/Library/Developer/CoreSimulator/Devices/5C24B81E-763F-4DBD-834A-F7CC59D1234F/data/Containers/Data/Application/833D4453-4D57-481E-BDBE-CC379B5C0E30/Library/Caches/audio_1730626770102.aac flutter: VideoCompress: You can try to subscribe to the flutter: compressProgress$ stream to know the compressing state. video_compress/SwiftVideoCompressPlugin.swift:203: Fatal error: Unexpectedly found nil while unwrapping an Optional value Lost connection to device.

    Continue reading...

Compartilhe esta Página