I am following this 5 minutes video to set up an audio recorder in Flutter.
When I click the ElevatedButton
to start recording the audio, it does change between play and stop, and an audio file is created, but the snapshot.hasData
is always false, so the Text
stays 00:00
during recording. The only information I found is about setSubscriptionDuration
, which I did set. I also tried flutter clean
, etc. What else can it be?
I’m using Flutter 3.3.8, on macOS, flutter_sound: ^9.1.9
. I’m running the app on a real iPhone XR with flutter run
I am new to flutter. I really appreciate any help you can provide!
I have
- StreamBuilder
StreamBuilder<RecordingDisposition>(
stream: recorder.onProgress,
builder: (context, snapshot) {
print('snapshot.hasData :${snapshot.hasData}');
final duration =
snapshot.hasData ? snapshot.data!.duration : Duration.zero;
print('duration :$duration');
String twoDigits(int n) => n.toString().padLeft(2, '0');
final twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
final twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return Text(
'$twoDigitMinutes:$twoDigitSeconds',
style: const TextStyle(
fontSize: 20,
),
);
},
),
- ElevatedButton
ElevatedButton(
child: Icon(
recorder.isRecording ? Icons.stop : Icons.mic,
size: 20,
),
onPressed: () async {
if (recorder.isRecording) {
await stop();
} else {
await record();
}
setState(() {});
},
)
- Initialize the recorder properly
final recorder = FlutterSoundRecorder();
Future<void> 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(
microseconds: 100,
),
);
}
@override
void initState() {
super.initState();
initRecorder();
}
This is what it looks like so far:
2
Answers
So, I found a solution, but the
StreamBuilder
question is not answered. Instead of usingStreamBuilder
, create a statefulTimerWidget
that's initialized by aValueNotifier
.change the microseconds: 100, to millisecond:100 in recorder.setSubscriptionDuration
like this