You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
534 lines
19 KiB
534 lines
19 KiB
import 'dart:io';
|
|
import 'dart:math' as math;
|
|
import 'package:audioplayers/audioplayers.dart';
|
|
import 'package:dating_touchme_app/extension/ex_widget.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
|
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
|
|
|
|
import '../../../generated/assets.dart';
|
|
import '../../../controller/message/voice_player_manager.dart';
|
|
import '../../../controller/global.dart';
|
|
import '../../../controller/message/chat_controller.dart';
|
|
|
|
class VoiceItem extends StatefulWidget {
|
|
final EMVoiceMessageBody voiceBody;
|
|
final String messageId; // 消息ID,用作音频的唯一标识
|
|
final EMMessage? message; // 添加消息对象以获取状态和错误码
|
|
final bool isSentByMe;
|
|
final bool showTime;
|
|
final String formattedTime;
|
|
final VoidCallback? onResend; // 添加重发回调
|
|
|
|
const VoiceItem({
|
|
required this.voiceBody,
|
|
required this.messageId,
|
|
this.message,
|
|
required this.isSentByMe,
|
|
required this.showTime,
|
|
required this.formattedTime,
|
|
this.onResend,
|
|
super.key,
|
|
});
|
|
|
|
@override
|
|
State<VoiceItem> createState() => _VoiceItemState();
|
|
}
|
|
|
|
class _VoiceItemState extends State<VoiceItem> with TickerProviderStateMixin {
|
|
final VoicePlayerManager _playerManager = VoicePlayerManager.instance;
|
|
late AnimationController _waveformAnimationController;
|
|
int _animationFrame = 0;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
// 创建波形动画控制器
|
|
_waveformAnimationController = AnimationController(
|
|
vsync: this,
|
|
duration: const Duration(milliseconds: 2000), // 2秒完成一个波浪周期
|
|
);
|
|
|
|
// 监听动画帧,更新波形
|
|
_waveformAnimationController.addListener(() {
|
|
if (mounted && _playerManager.isPlaying(widget.messageId)) {
|
|
setState(() {
|
|
// 使用动画值来计算波浪位置,让波浪从左到右传播
|
|
_animationFrame++;
|
|
});
|
|
}
|
|
});
|
|
|
|
// 监听播放状态变化
|
|
ever(_playerManager.currentPlayingId, (audioId) {
|
|
if (mounted) {
|
|
setState(() {});
|
|
// 根据播放状态控制动画
|
|
if (_playerManager.isPlaying(widget.messageId)) {
|
|
if (!_waveformAnimationController.isAnimating) {
|
|
_waveformAnimationController.repeat();
|
|
}
|
|
} else {
|
|
_waveformAnimationController.stop();
|
|
_waveformAnimationController.reset();
|
|
_animationFrame = 0;
|
|
}
|
|
}
|
|
});
|
|
ever(_playerManager.playerState, (state) {
|
|
if (mounted) {
|
|
setState(() {});
|
|
// 根据播放状态控制动画
|
|
if (state == PlayerState.playing &&
|
|
_playerManager.currentPlayingId.value == widget.messageId) {
|
|
_waveformAnimationController.repeat();
|
|
} else {
|
|
_waveformAnimationController.stop();
|
|
_animationFrame = 0;
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_waveformAnimationController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
// 处理播放/暂停
|
|
Future<void> _handlePlayPause() async {
|
|
try {
|
|
// 获取音频文件路径
|
|
String? filePath;
|
|
var localPath = widget.voiceBody.localPath;
|
|
final remotePath = widget.voiceBody.remotePath;
|
|
|
|
print('🔍 语音消息路径检查: localPath=$localPath, remotePath=$remotePath');
|
|
|
|
// 如果是接收到的消息且本地文件不存在或大小为0,先下载
|
|
if (!widget.isSentByMe && widget.message != null) {
|
|
final localFile = localPath.isNotEmpty ? File(localPath) : null;
|
|
bool needDownload = false;
|
|
|
|
if (localPath.isEmpty || localFile == null || !await localFile.exists()) {
|
|
needDownload = true;
|
|
print('📥 本地文件不存在,需要下载');
|
|
} else {
|
|
final fileSize = await localFile.length();
|
|
if (fileSize == 0) {
|
|
needDownload = true;
|
|
print('📥 本地文件大小为0,需要下载');
|
|
}
|
|
}
|
|
|
|
// 如果需要下载,先下载附件
|
|
if (needDownload) {
|
|
try {
|
|
print('📥 开始下载语音文件...');
|
|
await EMClient.getInstance.chatManager
|
|
.downloadAttachment(widget.message!);
|
|
|
|
// 下载后,等待一小段时间确保文件写入完成
|
|
await Future.delayed(Duration(milliseconds: 300));
|
|
|
|
// 下载后,从消息对象获取新的本地路径(下载后会自动更新 body 中的路径)
|
|
// 重新从消息对象获取 voiceBody,因为下载后路径会更新
|
|
if (widget.message!.body is EMVoiceMessageBody) {
|
|
final updatedVoiceBody = widget.message!.body as EMVoiceMessageBody;
|
|
localPath = updatedVoiceBody.localPath;
|
|
print('✅ 语音文件下载完成,新路径: $localPath');
|
|
} else {
|
|
print('⚠️ 消息 body 类型不是 EMVoiceMessageBody');
|
|
}
|
|
|
|
// 刷新状态
|
|
setState(() {});
|
|
} catch (e) {
|
|
print('❌ 下载语音文件失败: $e');
|
|
SmartDialog.showToast('下载语音文件失败: $e');
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 优先使用本地路径
|
|
if (localPath.isNotEmpty) {
|
|
final localFile = File(localPath);
|
|
if (await localFile.exists()) {
|
|
// 检查文件大小,确保文件有效
|
|
final fileSize = await localFile.length();
|
|
if (fileSize > 0) {
|
|
filePath = localPath;
|
|
print('✅ 使用本地音频文件: $localPath, 文件大小: $fileSize bytes');
|
|
} else {
|
|
print('⚠️ 本地音频文件大小为0: $localPath');
|
|
// 文件大小为0,尝试使用远程路径
|
|
if (remotePath != null && remotePath.isNotEmpty) {
|
|
if (remotePath.startsWith('http://') ||
|
|
remotePath.startsWith('https://')) {
|
|
filePath = remotePath;
|
|
print('✅ 使用远程音频文件: $remotePath');
|
|
} else {
|
|
SmartDialog.showToast('音频文件无效');
|
|
print('⚠️ 本地文件大小为0,远程路径不是URL: $remotePath');
|
|
return;
|
|
}
|
|
} else {
|
|
SmartDialog.showToast('音频文件无效');
|
|
print('⚠️ 本地文件大小为0,且没有远程路径');
|
|
return;
|
|
}
|
|
}
|
|
} else {
|
|
print('⚠️ 本地音频文件不存在: $localPath');
|
|
// 本地文件不存在,尝试使用远程路径
|
|
if (remotePath != null && remotePath.isNotEmpty) {
|
|
if (remotePath.startsWith('http://') ||
|
|
remotePath.startsWith('https://')) {
|
|
filePath = remotePath;
|
|
print('✅ 使用远程音频文件: $remotePath');
|
|
} else {
|
|
SmartDialog.showToast('音频文件不存在');
|
|
print('⚠️ 本地文件不存在,远程路径不是URL: $remotePath');
|
|
return;
|
|
}
|
|
} else {
|
|
SmartDialog.showToast('音频文件不存在');
|
|
print('⚠️ 本地和远程路径都无效');
|
|
return;
|
|
}
|
|
}
|
|
} else if (remotePath != null && remotePath.isNotEmpty) {
|
|
// 没有本地路径,直接使用远程路径
|
|
if (remotePath.startsWith('http://') ||
|
|
remotePath.startsWith('https://')) {
|
|
// 如果是HTTP URL,可以直接播放
|
|
filePath = remotePath;
|
|
print('✅ 使用远程音频文件(无本地路径): $remotePath');
|
|
} else {
|
|
SmartDialog.showToast('音频文件不存在');
|
|
print('⚠️ 远程路径不是URL: $remotePath');
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (filePath != null && filePath.isNotEmpty) {
|
|
print('🎵 开始播放音频: $filePath');
|
|
await _playerManager.play(widget.messageId, filePath);
|
|
} else {
|
|
SmartDialog.showToast('无法获取音频文件');
|
|
print('❌ 音频文件路径为空');
|
|
}
|
|
} catch (e) {
|
|
SmartDialog.showToast('播放失败: $e');
|
|
print('❌ 播放音频失败: $e');
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
// 获取语音时长(秒)
|
|
final duration = widget.voiceBody.duration;
|
|
final durationText = '${duration}s';
|
|
|
|
// 判断当前音频是否正在播放
|
|
final isPlaying = _playerManager.isPlaying(widget.messageId);
|
|
|
|
// 检查是否有金币信息(只对接收的消息显示)
|
|
final revenueInfo = _getRevenueInfo();
|
|
|
|
return Column(
|
|
children: [
|
|
// 显示时间
|
|
if (widget.showTime) _buildTimeLabel(),
|
|
Container(
|
|
padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
|
|
child: Row(
|
|
mainAxisAlignment: widget.isSentByMe
|
|
? MainAxisAlignment.end
|
|
: MainAxisAlignment.start,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
if (!widget.isSentByMe) _buildAvatar(),
|
|
if (!widget.isSentByMe) SizedBox(width: 8.w),
|
|
Column(
|
|
crossAxisAlignment: widget.isSentByMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
|
|
children: [
|
|
Container(
|
|
margin: EdgeInsets.only(top: 10.h),
|
|
padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
|
|
decoration: BoxDecoration(
|
|
color: widget.isSentByMe ? Color(0xff8E7BF6) : Colors.white,
|
|
borderRadius: BorderRadius.only(
|
|
topLeft: widget.isSentByMe
|
|
? Radius.circular(12.w)
|
|
: Radius.circular(0),
|
|
topRight: widget.isSentByMe
|
|
? Radius.circular(0)
|
|
: Radius.circular(12.w),
|
|
bottomLeft: Radius.circular(12.w),
|
|
bottomRight: Radius.circular(12.w),
|
|
),
|
|
),
|
|
child: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
// 播放按钮
|
|
Container(
|
|
width: 20.w,
|
|
height: 20.w,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
color: widget.isSentByMe ? Colors.white : Colors.black,
|
|
),
|
|
child: Icon(
|
|
isPlaying ? Icons.pause : Icons.play_arrow,
|
|
color: widget.isSentByMe
|
|
? Color(0xff8E7BF6)
|
|
: Colors.white,
|
|
size: 16.w,
|
|
),
|
|
),
|
|
SizedBox(width: 8.w),
|
|
// 时长文本
|
|
Text(
|
|
durationText,
|
|
style: TextStyle(
|
|
fontSize: 14.sp,
|
|
color: widget.isSentByMe ? Colors.white : Colors.black,
|
|
fontWeight: FontWeight.w500,
|
|
),
|
|
),
|
|
SizedBox(width: 8.w),
|
|
// 音频波形
|
|
_buildWaveform(),
|
|
],
|
|
),
|
|
).onTap(() {
|
|
_handlePlayPause();
|
|
}),
|
|
// 金币标签(只对接收的消息显示)
|
|
if (!widget.isSentByMe && revenueInfo != null)
|
|
Padding(
|
|
padding: EdgeInsets.only(top: 10.h),
|
|
child: _buildCoinLabel(revenueInfo),
|
|
),
|
|
],
|
|
),
|
|
if (widget.isSentByMe) SizedBox(width: 8.w),
|
|
if (widget.isSentByMe) _buildAvatar(),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
// 构建时间标签
|
|
Widget _buildTimeLabel() {
|
|
return Container(
|
|
alignment: Alignment.center,
|
|
padding: EdgeInsets.symmetric(horizontal: 16.w),
|
|
child: Container(
|
|
padding: EdgeInsets.symmetric(horizontal: 12.w),
|
|
child: Text(
|
|
widget.formattedTime,
|
|
style: TextStyle(fontSize: 12.sp, color: Colors.grey),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
// 构建头像
|
|
Widget _buildAvatar() {
|
|
String? avatarUrl;
|
|
|
|
if (widget.isSentByMe) {
|
|
// 发送的消息:使用当前登录用户的头像
|
|
// 优先从消息 attributes 中获取
|
|
try {
|
|
if (widget.message != null) {
|
|
final attributes = widget.message!.attributes;
|
|
if (attributes != null) {
|
|
avatarUrl = attributes['sender_avatarUrl'] as String? ??
|
|
attributes['avatarUrl'] as String?;
|
|
}
|
|
}
|
|
} catch (e) {
|
|
// 忽略错误
|
|
}
|
|
|
|
// 如果消息中没有,使用当前登录用户的头像
|
|
if (avatarUrl == null || avatarUrl.isEmpty) {
|
|
avatarUrl = GlobalData().userData?.profilePhoto;
|
|
}
|
|
} else {
|
|
// 接收的消息:使用发送者的头像
|
|
try {
|
|
if (widget.message != null) {
|
|
final attributes = widget.message!.attributes;
|
|
if (attributes != null) {
|
|
avatarUrl = attributes['sender_avatarUrl'] as String? ??
|
|
attributes['avatarUrl'] as String?;
|
|
}
|
|
}
|
|
} catch (e) {
|
|
// 忽略错误
|
|
}
|
|
|
|
// 如果消息中没有,尝试从 ChatController 获取对方用户头像
|
|
if ((avatarUrl == null || avatarUrl.isEmpty)) {
|
|
try {
|
|
// 尝试从 Get 获取 ChatController
|
|
final chatController = Get.find<ChatController>();
|
|
avatarUrl = chatController.userAvatarUrl;
|
|
} catch (e) {
|
|
// ChatController 可能不存在,忽略错误
|
|
}
|
|
}
|
|
}
|
|
|
|
// 清理头像URL(移除反引号)
|
|
if (avatarUrl != null && avatarUrl.isNotEmpty) {
|
|
avatarUrl = avatarUrl.trim().replaceAll('`', '');
|
|
}
|
|
|
|
return ClipOval(
|
|
child: avatarUrl != null && avatarUrl.isNotEmpty
|
|
? Image.network(
|
|
avatarUrl,
|
|
width: 40.w,
|
|
height: 40.w,
|
|
fit: BoxFit.cover,
|
|
errorBuilder: (context, error, stackTrace) {
|
|
return Image.asset(
|
|
Assets.imagesUserAvatar,
|
|
width: 40.w,
|
|
height: 40.w,
|
|
fit: BoxFit.cover,
|
|
);
|
|
},
|
|
)
|
|
: Image.asset(
|
|
Assets.imagesUserAvatar,
|
|
width: 40.w,
|
|
height: 40.w,
|
|
fit: BoxFit.cover,
|
|
),
|
|
);
|
|
}
|
|
|
|
// 获取金币信息(从 revenueInfo 或 coin_value 中获取)
|
|
String? _getRevenueInfo() {
|
|
try {
|
|
if (widget.message != null) {
|
|
final attributes = widget.message!.attributes;
|
|
if (attributes != null) {
|
|
// 优先从 revenueInfo 获取
|
|
final revenueInfo = attributes['revenueInfo'] as String?;
|
|
if (revenueInfo != null && revenueInfo.isNotEmpty) {
|
|
return revenueInfo;
|
|
}
|
|
// 如果没有 revenueInfo,从 coin_value 获取(可能是之前存储的 revenueInfo 值)
|
|
final coinValueStr = attributes['coin_value'] as String?;
|
|
if (coinValueStr != null && coinValueStr.isNotEmpty) {
|
|
return coinValueStr;
|
|
}
|
|
}
|
|
}
|
|
} catch (e) {
|
|
// 忽略错误
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// 构建金币标签
|
|
Widget _buildCoinLabel(String revenueInfo) {
|
|
return Container(
|
|
padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 3.h),
|
|
decoration: BoxDecoration(
|
|
color: Color.fromRGBO(0, 0, 0, 0.05),
|
|
borderRadius: BorderRadius.circular(12.w),
|
|
),
|
|
child: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Image.asset(
|
|
Assets.imagesImCoinIcon,
|
|
width: 10.w,
|
|
height: 10.w,
|
|
),
|
|
SizedBox(width: 2.w),
|
|
Text(
|
|
revenueInfo,
|
|
style: TextStyle(
|
|
fontSize: 9.sp,
|
|
color: Color.fromRGBO(255, 132, 0, 1),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
// 构建音频波形
|
|
Widget _buildWaveform() {
|
|
// 根据时长生成波形条数量(最多20个)
|
|
final barCount = (widget.voiceBody.duration / 2).ceil().clamp(5, 20);
|
|
final isPlaying = _playerManager.isPlaying(widget.messageId);
|
|
|
|
return SizedBox(
|
|
height: 16.h,
|
|
child: Row(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.center,
|
|
children: List.generate(barCount, (index) {
|
|
double height;
|
|
Color color;
|
|
|
|
if (isPlaying) {
|
|
// 播放时:波浪形动画效果
|
|
// 使用正弦波函数创建波浪效果,从左到右传播
|
|
// wavePhase: 时间因子(_animationFrame)让波浪移动,空间因子(index)让每个条的位置不同
|
|
// 移除模运算,让波浪连续传播
|
|
final wavePhase = _animationFrame * 0.15 + index * 0.6;
|
|
// 使用正弦波计算高度,范围在 4-16 之间
|
|
final sinValue = math.sin(wavePhase);
|
|
final normalizedValue = (sinValue + 1) / 2; // 归一化到 0-1
|
|
final baseHeight = 4 + normalizedValue * 12;
|
|
height = (baseHeight.clamp(4, 16)).h;
|
|
|
|
// 根据高度设置颜色透明度,创造渐变效果
|
|
final opacity = 0.5 + normalizedValue * 0.5;
|
|
color = widget.isSentByMe
|
|
? Colors.white.withOpacity(opacity.clamp(0.5, 1.0))
|
|
: Colors.grey.withOpacity(opacity.clamp(0.5, 0.9));
|
|
} else {
|
|
// 未播放时:静态波形
|
|
final random = (index * 7) % 5;
|
|
final baseHeight = 6 + random * 2;
|
|
height = (baseHeight.clamp(4, 16)).h;
|
|
color = widget.isSentByMe
|
|
? Colors.white.withOpacity(0.8)
|
|
: Colors.grey.withOpacity(0.6);
|
|
}
|
|
|
|
return AnimatedContainer(
|
|
duration: const Duration(milliseconds: 100),
|
|
curve: Curves.easeOut,
|
|
width: 2.w,
|
|
height: height,
|
|
margin: EdgeInsets.symmetric(horizontal: 1.w),
|
|
decoration: BoxDecoration(
|
|
color: color,
|
|
borderRadius: BorderRadius.circular(1.w),
|
|
),
|
|
);
|
|
}),
|
|
),
|
|
);
|
|
}
|
|
}
|