Skip to content

Commit 94a5480

Browse files
refactor: used existing AudioJack in soundmeter (#2748)
1 parent 63c3d3d commit 94a5480

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed

lib/providers/soundmeter_state_provider.dart

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,18 @@ import 'dart:async';
22
import 'dart:math';
33
import 'package:fl_chart/fl_chart.dart';
44
import 'package:pslab/others/logger_service.dart';
5-
import 'package:flutter_audio_capture/flutter_audio_capture.dart';
65
import 'package:flutter/foundation.dart';
76
import 'package:pslab/constants.dart';
7+
import 'package:pslab/others/audio_jack.dart';
88

99
class SoundMeterStateProvider extends ChangeNotifier {
1010
double _currentDb = 0.0;
1111
Timer? _timeTimer;
12+
Timer? _audioTimer;
1213
final List<double> _dbData = [];
1314
final List<double> _timeData = [];
1415
final List<FlSpot> dbChartData = [];
15-
FlutterAudioCapture? _audioCapture;
16+
AudioJack? _audioJack;
1617
double _startTime = 0;
1718
double _currentTime = 0;
1819
final int _maxLength = 50;
@@ -23,37 +24,34 @@ class SoundMeterStateProvider extends ChangeNotifier {
2324

2425
void initializeSensors() async {
2526
try {
26-
_audioCapture = FlutterAudioCapture();
27-
28-
await _audioCapture!.init();
27+
_audioJack = AudioJack();
28+
await _audioJack!.initialize();
29+
await _audioJack!.start();
2930

3031
_startTime = DateTime.now().millisecondsSinceEpoch / 1000.0;
32+
3133
_timeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
3234
_currentTime =
3335
(DateTime.now().millisecondsSinceEpoch / 1000.0) - _startTime;
3436
_updateData();
3537
notifyListeners();
3638
});
3739

38-
await _audioCapture!.start(
39-
(Float32List audioData) {
40-
_currentDb = _calculateDecibels(audioData);
41-
notifyListeners();
42-
},
43-
(error) {
44-
logger.e(
45-
"$soundMeterError $error",
46-
);
47-
},
48-
sampleRate: 44100,
49-
bufferSize: 4096,
50-
);
40+
_audioTimer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
41+
if (_audioJack != null && _audioJack!.isListening()) {
42+
final audioData = _audioJack!.read();
43+
if (audioData.isNotEmpty) {
44+
_currentDb = _calculateDecibels(audioData);
45+
notifyListeners();
46+
}
47+
}
48+
});
5149
} catch (e) {
5250
logger.e("$soundMeterInitialError $e");
5351
}
5452
}
5553

56-
double _calculateDecibels(Float32List audioData) {
54+
double _calculateDecibels(List<double> audioData) {
5755
if (audioData.isEmpty) return 0.0;
5856

5957
double sum = 0;
@@ -71,9 +69,11 @@ class SoundMeterStateProvider extends ChangeNotifier {
7169
return dbSPL.clamp(20.0, 120.0);
7270
}
7371

74-
void disposeSensors() {
75-
_audioCapture?.stop();
72+
void disposeSensors() async {
7673
_timeTimer?.cancel();
74+
_audioTimer?.cancel();
75+
await _audioJack?.close();
76+
_audioJack = null;
7777
}
7878

7979
@override

0 commit comments

Comments
 (0)