Skip to content

feat: implemented the sound meter #2739

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/constants.dart
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,7 @@ String lx = 'Lx';
String maxScaleError = 'Max Scale';
String lightSensorError = 'Light sensor error:';
String lightSensorInitialError = 'Failed to initialize light sensor:';
String soundMeterError = 'Sound sensor error:';
String soundMeterInitialError = 'Sound sensor initialization error:';
String db = 'dB';
String soundMeterTitle = 'Sound Meter';
3 changes: 3 additions & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import 'package:pslab/view/settings_screen.dart';
import 'package:pslab/view/about_us_screen.dart';
import 'package:pslab/view/software_licenses_screen.dart';
import 'package:pslab/others/theme.dart';
import 'package:pslab/view/soundmeter_screen.dart';
import 'constants.dart';

void main() {
Expand All @@ -33,6 +34,7 @@ void main() {

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
_preCacheImages(context);
Expand All @@ -53,6 +55,7 @@ class MyApp extends StatelessWidget {
'/accelerometer': (context) => const AccelerometerScreen(),
'/gyroscope': (context) => const GyroscopeScreen(),
'/luxmeter': (context) => const LuxMeterScreen(),
'/soundmeter': (context) => const SoundMeterScreen(),
},
);
}
Expand Down
123 changes: 123 additions & 0 deletions lib/providers/soundmeter_state_provider.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import 'dart:async';
import 'dart:math';
import 'package:fl_chart/fl_chart.dart';
import 'package:pslab/others/logger_service.dart';
import 'package:flutter_audio_capture/flutter_audio_capture.dart';
import 'package:flutter/foundation.dart';
import 'package:pslab/constants.dart';

class SoundMeterStateProvider extends ChangeNotifier {
double _currentDb = 0.0;
Timer? _timeTimer;
final List<double> _dbData = [];
final List<double> _timeData = [];
final List<FlSpot> dbChartData = [];
FlutterAudioCapture? _audioCapture;
double _startTime = 0;
double _currentTime = 0;
final int _maxLength = 50;
double _dbMin = 0;
double _dbMax = 0;
double _dbSum = 0;
int _dataCount = 0;

void initializeSensors() async {
try {
_audioCapture = FlutterAudioCapture();

await _audioCapture!.init();

_startTime = DateTime.now().millisecondsSinceEpoch / 1000.0;
_timeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
_currentTime =
(DateTime.now().millisecondsSinceEpoch / 1000.0) - _startTime;
_updateData();
notifyListeners();
});

await _audioCapture!.start(
(Float32List audioData) {
_currentDb = _calculateDecibels(audioData);
notifyListeners();
},
(error) {
logger.e(
"$soundMeterError $error",
);
},
sampleRate: 44100,
bufferSize: 4096,
);
} catch (e) {
logger.e("$soundMeterInitialError $e");
}
}

double _calculateDecibels(Float32List audioData) {
if (audioData.isEmpty) return 0.0;

double sum = 0;
for (double sample in audioData) {
sum += sample * sample;
}
double rms = sqrt(sum / audioData.length);

if (rms <= 0) return 0.0;

double dbFS = 20 * log(rms) / ln10;

double dbSPL = dbFS + 94;

return dbSPL.clamp(20.0, 120.0);
}

void disposeSensors() {
_audioCapture?.stop();
_timeTimer?.cancel();
}

@override
void dispose() {
disposeSensors();
super.dispose();
}

void _updateData() {
final db = _currentDb;
final time = _currentTime;
_dbData.add(db);
_timeData.add(time);
_dbSum += db;
_dataCount++;
if (_dbData.length > _maxLength) {
final removedValue = _dbData.removeAt(0);
_timeData.removeAt(0);
_dbSum -= removedValue;
_dataCount--;
}
if (_dbData.isNotEmpty) {
_dbMin = _dbData.reduce(min);
_dbMax = _dbData.reduce(max);
}
dbChartData.clear();
for (int i = 0; i < _dbData.length; i++) {
dbChartData.add(FlSpot(_timeData[i], _dbData[i]));
}
notifyListeners();
}

double getCurrentDb() => _currentDb;
double getMinDb() => _dbMin;
double getMaxDb() => _dbMax;
double getAverageDb() => _dataCount > 0 ? _dbSum / _dataCount : 0.0;
List<FlSpot> getDbChartData() => dbChartData;
int getDataLength() => dbChartData.length;
double getCurrentTime() => _currentTime;
double getMaxTime() => _timeData.isNotEmpty ? _timeData.last : 0;
double getMinTime() => _timeData.isNotEmpty ? _timeData.first : 0;
double getTimeInterval() {
if (_currentTime <= 10) return 2;
if (_currentTime <= 30) return 5;
return 10;
}
}
12 changes: 12 additions & 0 deletions lib/view/instruments_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ class _InstrumentsScreenState extends State<InstrumentsScreen> {
);
}
break;
case 15:
if (Navigator.canPop(context) &&
ModalRoute.of(context)?.settings.name == '/soundmeter') {
Navigator.popUntil(context, ModalRoute.withName('/soundmeter'));
} else {
Navigator.pushNamedAndRemoveUntil(
context,
'/soundmeter',
(route) => route.isFirst,
);
}
break;
default:
break;
}
Expand Down
Loading