Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'dart:io';
- import 'package:flutter/material.dart';
- import 'package:intl/intl.dart';
- import 'package:just_audio/just_audio.dart' as ap;
- import 'package:mailer/mailer.dart';
- import 'package:mailer/smtp_server.dart';
- import 'package:record/record.dart';
- class AudioRecorder extends StatefulWidget {
- final void Function(String path) onStop;
- const AudioRecorder({required this.onStop});
- @override
- _AudioRecorderState createState() => _AudioRecorderState();
- }
- class _AudioRecorderState extends State<AudioRecorder> {
- bool _isRecording = false;
- bool _isPaused = false;
- int _recordDuration = 0;
- Timer? _timer;
- Timer? _ampTimer;
- final _audioRecorder = Record();
- @override
- void initState() {
- _isRecording = false;
- super.initState();
- }
- @override
- void dispose() {
- _timer?.cancel();
- _ampTimer?.cancel();
- _audioRecorder.dispose();
- super.dispose();
- }
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- home: Scaffold(
- body: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Row(
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- _buildRecordStopControl(),
- const SizedBox(width: 20),
- _buildPauseResumeControl(),
- const SizedBox(width: 20),
- _buildText(),
- ],
- ),
- ],
- ),
- ),
- );
- }
- Widget _buildRecordStopControl() {
- late Icon icon;
- late Color color;
- if (_isRecording || _isPaused) {
- icon = Icon(Icons.stop, color: Colors.red, size: 30);
- color = Colors.red.withOpacity(0.1);
- } else {
- final theme = Theme.of(context);
- icon = Icon(Icons.mic, color: theme.primaryColor, size: 30);
- color = theme.primaryColor.withOpacity(0.1);
- }
- return ClipOval(
- child: Material(
- color: color,
- child: InkWell(
- child: SizedBox(width: 56, height: 56, child: icon),
- onTap: () {
- _isRecording ? _stop() : _start();
- },
- ),
- ),
- );
- }
- Widget _buildPauseResumeControl() {
- if (!_isRecording && !_isPaused) {
- return const SizedBox.shrink();
- }
- late Icon icon;
- late Color color;
- if (!_isPaused) {
- icon = Icon(Icons.pause, color: Colors.red, size: 30);
- color = Colors.red.withOpacity(0.1);
- } else {
- final theme = Theme.of(context);
- icon = Icon(Icons.play_arrow, color: Colors.red, size: 30);
- color = theme.primaryColor.withOpacity(0.1);
- }
- return ClipOval(
- child: Material(
- color: color,
- child: InkWell(
- child: SizedBox(width: 56, height: 56, child: icon),
- onTap: () {
- _isPaused ? _resume() : _pause();
- },
- ),
- ),
- );
- }
- Widget _buildText() {
- if (_isRecording || _isPaused) {
- return _buildTimer();
- }
- return Text("");
- }
- Widget _buildTimer() {
- final String minutes = _formatNumber(_recordDuration ~/ 60);
- final String seconds = _formatNumber(_recordDuration % 60);
- return Text(
- '$minutes : $seconds',
- style: TextStyle(color: Colors.red),
- );
- }
- String _formatNumber(int number) {
- String numberStr = number.toString();
- if (number < 10) {
- numberStr = '0' + numberStr;
- }
- return numberStr;
- }
- Future<void> _start() async {
- try {
- if (await _audioRecorder.hasPermission()) {
- await _audioRecorder.start();
- bool isRecording = await _audioRecorder.isRecording();
- setState(() {
- _isRecording = isRecording;
- _recordDuration = 0;
- });
- _startTimer();
- }
- } catch (e) {
- print(e);
- }
- }
- Future<void> _stop() async {
- _timer?.cancel();
- _ampTimer?.cancel();
- final path = await _audioRecorder.stop();
- widget.onStop(path!);
- setState(() => _isRecording = false);
- }
- Future<void> _pause() async {
- _timer?.cancel();
- _ampTimer?.cancel();
- await _audioRecorder.pause();
- setState(() => _isPaused = true);
- }
- Future<void> _resume() async {
- _startTimer();
- await _audioRecorder.resume();
- setState(() => _isPaused = false);
- }
- void _startTimer() {
- _timer?.cancel();
- _ampTimer?.cancel();
- _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
- setState(() => _recordDuration++);
- });
- _ampTimer =
- Timer.periodic(const Duration(milliseconds: 200), (Timer t) async {
- setState(() {});
- });
- }
- }
- void main() {
- runApp(MyApp());
- }
- class MyApp extends StatefulWidget {
- @override
- _MyAppState createState() => _MyAppState();
- }
- class _MyAppState extends State<MyApp> {
- bool showPlayer = false;
- ap.AudioSource? audioSource;
- @override
- void initState() {
- showPlayer = false;
- super.initState();
- }
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- home: Scaffold(
- body: Center(
- child: showPlayer
- ? Padding(
- padding: EdgeInsets.symmetric(horizontal: 25),
- child: AudioPlayer(
- source: audioSource!,
- onDelete: () {
- setState(() => showPlayer = false);
- },
- ),
- )
- : AudioRecorder(
- onStop: (path) {
- setState(() {
- audioSource = ap.AudioSource.uri(Uri.parse(path));
- showPlayer = true;
- });
- },
- ),
- ),
- ),
- );
- }
- }
- class AudioPlayer extends StatefulWidget {
- /// Path from where to play recorded audio
- final ap.AudioSource source;
- /// Callback when audio file should be removed
- /// Setting this to null hides the delete button
- final VoidCallback onDelete;
- const AudioPlayer({
- required this.source,
- required this.onDelete,
- });
- @override
- AudioPlayerState createState() => AudioPlayerState();
- }
- class AudioPlayerState extends State<AudioPlayer> {
- static const double _controlSize = 56;
- static const double _deleteBtnSize = 24;
- final _audioPlayer = ap.AudioPlayer();
- late StreamSubscription<ap.PlayerState> _playerStateChangedSubscription;
- late StreamSubscription<Duration?> _durationChangedSubscription;
- late StreamSubscription<Duration> _positionChangedSubscription;
- @override
- void initState() {
- _playerStateChangedSubscription =
- _audioPlayer.playerStateStream.listen((state) async {
- if (state.processingState == ap.ProcessingState.completed) {
- await stop();
- }
- setState(() {});
- });
- _positionChangedSubscription =
- _audioPlayer.positionStream.listen((position) => setState(() {}));
- _durationChangedSubscription =
- _audioPlayer.durationStream.listen((duration) => setState(() {}));
- _init();
- super.initState();
- }
- Future<void> _init() async {
- await _audioPlayer.setAudioSource(widget.source);
- }
- @override
- void dispose() {
- _playerStateChangedSubscription.cancel();
- _positionChangedSubscription.cancel();
- _durationChangedSubscription.cancel();
- _audioPlayer.dispose();
- super.dispose();
- }
- @override
- Widget build(BuildContext context) {
- return LayoutBuilder(
- builder: (context, constraints) {
- return Column(
- mainAxisSize: MainAxisSize.max,
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: <Widget>[
- _buildControl(),
- _buildSlider(constraints.maxWidth),
- IconButton(
- icon: Icon(Icons.delete,
- color: const Color(0xFF73748D), size: _deleteBtnSize),
- onPressed: () {
- _audioPlayer.stop().then((value) => widget.onDelete());
- },
- ),
- ElevatedButton(
- style: ElevatedButton.styleFrom(
- minimumSize: Size(175, 50),
- primary: Colors.white,
- onPrimary: Colors.black,
- ),
- child: Text('verstuur',
- style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
- onPressed: () {
- audioVerzenden();
- //Navigator.of(context).pop();
- },
- )
- ],
- );
- },
- );
- }
- Widget _buildControl() {
- Icon icon;
- Color color;
- if (_audioPlayer.playerState.playing) {
- icon = Icon(Icons.pause, color: Colors.red, size: 30);
- color = Colors.red.withOpacity(0.1);
- } else {
- final theme = Theme.of(context);
- icon = Icon(Icons.play_arrow, color: theme.primaryColor, size: 30);
- color = theme.primaryColor.withOpacity(0.1);
- }
- return ClipOval(
- child: Material(
- color: color,
- child: InkWell(
- child:
- SizedBox(width: _controlSize, height: _controlSize, child: icon),
- onTap: () {
- if (_audioPlayer.playerState.playing) {
- pause();
- } else {
- play();
- }
- },
- ),
- ),
- );
- }
- Widget _buildSlider(double widgetWidth) {
- final position = _audioPlayer.position;
- final duration = _audioPlayer.duration;
- bool canSetValue = false;
- if (duration != null) {
- canSetValue = position.inMilliseconds > 0;
- canSetValue &= position.inMilliseconds < duration.inMilliseconds;
- }
- double width = widgetWidth - _controlSize - _deleteBtnSize;
- width -= _deleteBtnSize;
- return SizedBox(
- width: width,
- child: Slider(
- activeColor: Theme.of(context).primaryColor,
- inactiveColor: Theme.of(context).accentColor,
- onChanged: (v) {
- if (duration != null) {
- final position = v * duration.inMilliseconds;
- _audioPlayer.seek(Duration(milliseconds: position.round()));
- }
- },
- value: canSetValue && duration != null
- ? position.inMilliseconds / duration.inMilliseconds
- : 0.0,
- ),
- );
- }
- Future<void> play() {
- return _audioPlayer.play();
- }
- Future<void> pause() {
- return _audioPlayer.pause();
- }
- Future<void> stop() async {
- await _audioPlayer.stop();
- return _audioPlayer.seek(const Duration(milliseconds: 0));
- }
- audioVerzenden() async {
- final smtpServer = SmtpServer("server",
- username: 'username',
- password: 'password',
- allowInsecure: true,
- ignoreBadCertificate: true);
- final datumOpmaak = DateFormat('dd-MM-yyyy H:mm');
- // Create our message.
- final message = Message()
- ..from = Address('from@email.com', 'From name')
- ..recipients.add('reciepient@gmail.com')
- ..subject =
- 'Test Dart Mailer library :: 😀 :: ${datumOpmaak.format(DateTime.now())}'
- ..text = 'This is the plain text.\nThis is line 2 of the text part.'
- ..attachments = [FileAttachment(File.fromUri(Uri.parse(filePath)))];
- try {
- final sendReport = await send(message, smtpServer);
- print('Message sent: ' + sendReport.toString());
- } on MailerException catch (e) {
- print('Message not sent.');
- for (var p in e.problems) {
- print('Problem: ${p.code}: ${p.msg}');
- }
- }
- }
- // DONE
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement