Created
September 15, 2022 15:03
-
-
Save boring-km/c8fb0998873e074b4a63a7f04238843e to your computer and use it in GitHub Desktop.
How to stop record audio automatically in Flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:audioplayers/audioplayers.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:path_provider/path_provider.dart'; | |
import 'package:record/record.dart'; | |
void main() { | |
runApp(const MaterialApp( | |
home: AutoRecordStopPage(), | |
)); | |
} | |
class AutoRecordStopPage extends StatefulWidget { | |
const AutoRecordStopPage({Key? key}) : super(key: key); | |
@override | |
State<AutoRecordStopPage> createState() => _AutoRecordStopPageState(); | |
} | |
class _AutoRecordStopPageState extends State<AutoRecordStopPage> { | |
final record = Record(); | |
final player = AudioPlayer(); | |
String savePath = ''; | |
@override | |
void initState() { | |
getTemporaryDirectory().then((tempDir) { | |
setState(() { | |
savePath = '${tempDir.path}/temp.m4a'; | |
}); | |
}); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: Column( | |
mainAxisSize: MainAxisSize.min, | |
children: [ | |
ElevatedButton( | |
onPressed: () { | |
startAutoRecord(savePath); | |
}, | |
child: const Text('녹음 시작'), | |
), | |
ElevatedButton( | |
onPressed: () { | |
player.play(DeviceFileSource(savePath)); | |
}, | |
child: const Text('들어 보기'), | |
), | |
], | |
), | |
), | |
); | |
} | |
startAutoRecord(String savePath) async { | |
if (await record.hasPermission() && await record.isRecording() == false) { | |
try { | |
debugPrint('녹음 시작'); | |
record.start(path: savePath); | |
await waitAudioFinished( | |
record, | |
savePath: savePath, | |
callback: () { | |
record.stop(); | |
}, | |
); | |
} catch (error) { | |
debugPrint(error.toString()); | |
} | |
} | |
} | |
Future<void> waitAudioFinished( | |
Record record, { | |
required String savePath, | |
required Function callback, | |
}) async { | |
// 1초 대기 | |
Future.delayed(const Duration(seconds: 1), () async { | |
var stopCount = 0; | |
for (var idx = 0; idx < 100000; idx++) { | |
if (await record.isRecording()) { | |
await Future.delayed(const Duration(milliseconds: 50), () async { | |
final amplitude = await record.getAmplitude(); | |
final current = amplitude.current; | |
debugPrint('current: $current'); | |
if (current.toString() != '-Infinity') { | |
if (current < -25) { | |
stopCount += 1; | |
} else { | |
stopCount = 0; | |
} | |
if (stopCount > 10) { | |
callback.call(); | |
} | |
} | |
}); | |
} else { | |
break; | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment