flutter_kit_mic 0.0.1
flutter_kit_mic: ^0.0.1 copied to clipboard
Private plugins / packages
example/lib/main.dart
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_kit_mic/flutter_kit_mic.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
final _flutterKitMicPlugin = FlutterKitMic();
@override
void initState() {
super.initState();
initPlatformState();
_sub = FlutterKitMic.pcmStream();
_sub!.listen((bytes) {
// bytes: Int16 小端,单声道
final rms = _rmsPcm16Le(bytes);
final ref = 20e-6; // 参考声压(仅示例)
setState(() {
print('=================>. ${rms}');
db = 20 * log(max(rms, 1.0) / ref);
});
// TODO: 用 db 驱动你的 LED
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
// We also handle the message potentially returning null.
try {
platformVersion = await FlutterKitMic.getPlatformVersion() ?? 'Unknown platform version';
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
Stream<Uint8List>? _sub;
double db = 0;
Future<void> startMic() async {
final ok = await FlutterKitMic.requestPermission();
if (!ok) {
// 引导用户去设置里开启
return;
}
await FlutterKitMic.startRecorder(
androidRunInForeground: true,
androidNotificationTitle: 'Mic running',
androidNotificationText: 'Listening in background',
);
}
double _rmsPcm16Le(Uint8List bytes) {
final len = bytes.lengthInBytes ~/ 2;
double sum = 0;
for (int i = 0; i < len; i++) {
final lo = bytes[i * 2];
final hi = bytes[i * 2 + 1];
int s = (hi << 8) | lo;
if (s > 32767) s -= 65536;
sum += (s * s).toDouble();
}
return sqrt(sum / max(1, len)) / 32768.0; // 归一化
}
Future<void> stopMic() async {
setState(() {
db = 0;
});
await FlutterKitMic.stopRecorder();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Plugin example app')),
body: Column(
children: [
Center(child: Text('Running on: $_platformVersion\n')),
Text('db mic: $db\n'),
SizedBox(
width: 80,
height: 40,
child: InkWell(
child: Text('recorder'),
onTap: () {
startMic();
},
),
),
SizedBox(
width: 80,
height: 40,
child: InkWell(
child: Text('stop'),
onTap: () {
stopMic();
},
),
),
],
),
),
);
}
}