Files
zh-chat-flutter/lib/views/conversation/widgets/show_sound_message.dart
2022-10-26 14:53:22 +08:00

136 lines
3.8 KiB
Dart

import 'dart:io';
import 'dart:math';
import 'package:chat/configs/app_colors.dart';
import 'package:chat/configs/app_size.dart';
import 'package:chat/utils/sound_record.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';
class ShowSoundMessage extends StatefulWidget {
final V2TimMessage message;
const ShowSoundMessage(this.message, {Key? key}) : super(key: key);
@override
State<ShowSoundMessage> createState() => _ShowSoundMessageState();
}
class _ShowSoundMessageState extends State<ShowSoundMessage> {
bool isPlaying = false;
@override
void initState() {
super.initState();
SoundPlayer.playStateListener(listener: (_) {
if (_.playState == "complete") {
if (mounted) {
setState(() {
isPlaying = false;
});
}
}
});
SoundPlayer.setSoundInterruptListener(() {
if (mounted) {
setState(() {
isPlaying = false;
});
}
});
}
void stopAndDispose() async {
if (isPlaying) {
await SoundPlayer.stop();
SoundPlayer.dispose();
}
}
_playSound() async {
if (!SoundPlayer.isInited) {
bool hasMicrophonePermission =
await Permission.microphone.request().isGranted;
bool hasStoragePermission =
Platform.isIOS || await Permission.storage.request().isGranted;
if (hasMicrophonePermission && hasStoragePermission) {
SoundPlayer.initSoundPlayer();
}
}
if (isPlaying) {
SoundPlayer.stop();
setState(() {
isPlaying = false;
});
} else {
SoundPlayer.play(url: widget.message.soundElem!.url!);
setState(() {
isPlaying = true;
});
}
}
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
_playSound();
},
child: Container(
constraints: BoxConstraints(
maxWidth: Get.width * 0.618,
minWidth: 64,
minHeight: 43,
),
width:
(widget.message.soundElem!.duration! / 60) * (Get.width * 0.618) +
64,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: widget.message.isSelf! ? AppColors.primary : AppColors.white,
),
child: Row(
mainAxisAlignment: widget.message.isSelf!
? MainAxisAlignment.start
: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'${widget.message.soundElem!.duration}"',
style: TextStyle(
fontSize: AppSize.fontSize,
color: widget.message.isSelf!
? AppColors.white
: AppColors.primary,
),
),
const SizedBox(width: 4),
Transform.rotate(
angle: widget.message.isSelf! ? pi : 0,
child: const Icon(
Icons.volume_up,
size: 18,
color: AppColors.white,
),
),
// Image.asset(
// widget.message.isSelf!
// ? isPlaying
// ? 'assets/chats/play_voice_send.gif'
// : 'assets/chats/voice_send.png'
// : isPlaying
// ? 'assets/chats/play_voice_receive.gif'
// : 'assets/chats/voice_receive.png',
// height: 16,
// color:
// widget.message.isSelf! ? AppColors.white : AppColors.primary,
// ),
],
),
),
);
}
}