Files
keyboard/keyBoard/Class/AiTalk/V/KBChatTableView.m

702 lines
26 KiB
Mathematica
Raw Normal View History

2026-01-23 21:51:37 +08:00
//
// KBChatTableView.m
// keyBoard
//
// Created by Kiro on 2026/1/23.
//
#import "KBChatTableView.h"
#import "KBAiChatMessage.h"
#import "KBChatUserMessageCell.h"
#import "KBChatAssistantMessageCell.h"
#import "KBChatTimeCell.h"
#import "AiVM.h"
2026-01-26 20:36:51 +08:00
#import <MJRefresh/MJRefresh.h>
2026-01-23 21:51:37 +08:00
#import <Masonry/Masonry.h>
#import <AVFoundation/AVFoundation.h>
static NSString * const kUserCellIdentifier = @"KBChatUserMessageCell";
static NSString * const kAssistantCellIdentifier = @"KBChatAssistantMessageCell";
static NSString * const kTimeCellIdentifier = @"KBChatTimeCell";
///
static const NSTimeInterval kTimestampInterval = 5 * 60; // 5
@interface KBChatTableView () <UITableViewDataSource, UITableViewDelegate, KBChatAssistantMessageCellDelegate, AVAudioPlayerDelegate>
2026-01-28 17:21:19 +08:00
@property (nonatomic, strong) BaseTableView *tableView;
2026-01-23 21:51:37 +08:00
@property (nonatomic, strong) NSMutableArray<KBAiChatMessage *> *messages;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic, strong) NSIndexPath *playingCellIndexPath;
@property (nonatomic, strong) AiVM *aiVM;
2026-01-26 20:36:51 +08:00
@property (nonatomic, assign) BOOL hasMoreData;
2026-01-27 16:28:17 +08:00
@property (nonatomic, assign) CGFloat contentBottomInset;
2026-01-23 21:51:37 +08:00
@end
@implementation KBChatTableView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setup];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
[self setup];
}
return self;
}
- (void)setup {
self.messages = [[NSMutableArray alloc] init];
self.aiVM = [[AiVM alloc] init];
2026-01-26 20:36:51 +08:00
self.hasMoreData = YES;
2026-01-23 21:51:37 +08:00
// TableView
2026-01-28 17:21:19 +08:00
self.tableView = [[BaseTableView alloc] initWithFrame:self.bounds
2026-01-23 21:51:37 +08:00
style:UITableViewStylePlain];
2026-01-28 17:21:19 +08:00
self.tableView.useEmptyDataSet = false;
2026-01-23 21:51:37 +08:00
self.tableView.dataSource = self;
self.tableView.delegate = self;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundColor = [UIColor clearColor];
2026-01-27 17:03:16 +08:00
// 使0
self.tableView.estimatedRowHeight = 80;
self.tableView.estimatedSectionHeaderHeight = 0;
self.tableView.estimatedSectionFooterHeight = 0;
2026-01-23 21:51:37 +08:00
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.showsVerticalScrollIndicator = YES;
2026-01-27 17:03:16 +08:00
// CollectionView
if (@available(iOS 11.0, *)) {
self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
}
2026-01-23 21:51:37 +08:00
[self addSubview:self.tableView];
// Cell
[self.tableView registerClass:[KBChatUserMessageCell class]
forCellReuseIdentifier:kUserCellIdentifier];
[self.tableView registerClass:[KBChatAssistantMessageCell class]
forCellReuseIdentifier:kAssistantCellIdentifier];
[self.tableView registerClass:[KBChatTimeCell class]
forCellReuseIdentifier:kTimeCellIdentifier];
//
[self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
2026-01-27 16:28:17 +08:00
make.edges.equalTo(self);
2026-01-23 21:51:37 +08:00
}];
2026-01-26 20:36:51 +08:00
2026-01-27 18:53:19 +08:00
// contentBottomInset chatView
self.contentBottomInset = 20; //
2026-01-27 16:28:17 +08:00
[self updateContentBottomInset:self.contentBottomInset];
2026-01-26 20:36:51 +08:00
__weak typeof(self) weakSelf = self;
self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
if (!strongSelf.hasMoreData) {
[strongSelf.tableView.mj_footer endRefreshingWithNoMoreData];
return;
}
if ([strongSelf.delegate respondsToSelector:@selector(chatTableViewDidTriggerLoadMore:)]) {
[strongSelf.delegate chatTableViewDidTriggerLoadMore:strongSelf];
} else {
[strongSelf.tableView.mj_footer endRefreshing];
}
}];
2026-01-28 15:32:56 +08:00
// "已经全部加载完毕"
MJRefreshAutoNormalFooter *footer = (MJRefreshAutoNormalFooter *)self.tableView.mj_footer;
footer.stateLabel.hidden = YES; //
footer.refreshingBlock = footer.refreshingBlock; //
2026-01-26 20:36:51 +08:00
self.tableView.mj_footer.hidden = YES;
2026-01-23 21:51:37 +08:00
}
#pragma mark - Public Methods
- (void)addUserMessage:(NSString *)text {
KBAiChatMessage *message = [KBAiChatMessage userMessageWithText:text];
2026-01-26 20:36:51 +08:00
[self addMessage:message autoScroll:YES];
2026-01-23 21:51:37 +08:00
}
- (void)addAssistantMessage:(NSString *)text
audioDuration:(NSTimeInterval)duration
audioData:(NSData *)audioData {
KBAiChatMessage *message = [KBAiChatMessage assistantMessageWithText:text
audioDuration:duration
audioData:audioData];
2026-01-26 20:36:51 +08:00
[self addMessage:message autoScroll:YES];
2026-01-23 21:51:37 +08:00
}
- (void)addAssistantMessage:(NSString *)text
audioId:(NSString *)audioId {
KBAiChatMessage *message = [KBAiChatMessage assistantMessageWithText:text
audioId:audioId];
message.needsTypewriterEffect = YES; //
2026-01-26 20:36:51 +08:00
[self addMessage:message autoScroll:YES];
2026-01-23 21:51:37 +08:00
}
- (void)updateLastAssistantMessage:(NSString *)text {
// AI
for (NSInteger i = self.messages.count - 1; i >= 0; i--) {
KBAiChatMessage *message = self.messages[i];
if (message.type == KBAiChatMessageTypeAssistant && !message.isComplete) {
NSLog(@"[KBChatTableView] 更新最后一条 AI 消息 - 索引: %ld, 文本长度: %lu, needsTypewriter: %d",
(long)i, (unsigned long)text.length, message.needsTypewriterEffect);
message.text = text;
// Cell Cell
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
KBChatAssistantMessageCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[KBChatAssistantMessageCell class]]) {
NSLog(@"[KBChatTableView] 找到 Cell直接配置消息");
// configureWithMessage Cell 使
[cell configureWithMessage:message];
} else {
NSLog(@"[KBChatTableView] 未找到 Cell 或类型不匹配");
}
return;
}
}
//
NSLog(@"[KBChatTableView] 未找到未完成的 AI 消息,添加新消息");
[self addAssistantMessage:text audioDuration:0 audioData:nil];
}
- (void)markLastAssistantMessageComplete {
for (NSInteger i = self.messages.count - 1; i >= 0; i--) {
KBAiChatMessage *message = self.messages[i];
if (message.type == KBAiChatMessageTypeAssistant) {
NSLog(@"[KBChatTableView] 标记消息完成 - 索引: %ld, 文本: %@", (long)i, message.text);
message.isComplete = YES;
message.needsTypewriterEffect = NO; //
// Cell
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
[self.tableView reloadRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationNone];
return;
}
}
}
- (void)clearMessages {
[self.messages removeAllObjects];
[self.tableView reloadData];
2026-01-26 20:36:51 +08:00
[self updateFooterVisibility];
2026-01-23 21:51:37 +08:00
}
- (void)scrollToBottom {
2026-01-27 17:03:16 +08:00
[self scrollToBottomAnimated:YES];
}
- (void)scrollToBottomAnimated:(BOOL)animated {
2026-01-23 21:51:37 +08:00
if (self.messages.count == 0) return;
2026-01-27 17:03:16 +08:00
// 使 layoutIfNeeded
[self.tableView layoutIfNeeded];
2026-01-23 21:51:37 +08:00
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:self.messages.count - 1
inSection:0];
2026-01-27 17:03:16 +08:00
//
2026-01-23 21:51:37 +08:00
[self.tableView scrollToRowAtIndexPath:lastIndexPath
atScrollPosition:UITableViewScrollPositionBottom
2026-01-27 17:03:16 +08:00
animated:animated];
2026-01-23 21:51:37 +08:00
}
2026-01-26 20:36:51 +08:00
#pragma mark - Public Helpers
- (void)endLoadMoreWithHasMoreData:(BOOL)hasMoreData {
self.hasMoreData = hasMoreData;
if (hasMoreData) {
[self.tableView.mj_footer endRefreshing];
} else {
[self.tableView.mj_footer endRefreshingWithNoMoreData];
}
[self updateFooterVisibility];
}
- (void)resetNoMoreData {
self.hasMoreData = YES;
[self.tableView.mj_footer resetNoMoreData];
[self updateFooterVisibility];
}
2026-01-27 16:28:17 +08:00
- (void)updateContentBottomInset:(CGFloat)bottomInset {
self.contentBottomInset = bottomInset;
UIEdgeInsets insets = self.tableView.contentInset;
insets.bottom = bottomInset;
self.tableView.contentInset = insets;
self.tableView.scrollIndicatorInsets = insets;
}
2026-01-26 20:36:51 +08:00
- (void)addMessage:(KBAiChatMessage *)message
autoScroll:(BOOL)autoScroll {
if (!message) {
return;
}
if (message.type == KBAiChatMessageTypeAssistant &&
message.needsTypewriterEffect &&
!message.isComplete) {
[self stopPreviousIncompleteAssistantMessageIfNeeded];
}
NSInteger oldCount = self.messages.count;
[self insertMessageWithTimestamp:message];
NSInteger newCount = self.messages.count;
NSInteger insertedCount = newCount - oldCount;
if (insertedCount > 0) {
NSMutableArray *indexPaths = [NSMutableArray array];
for (NSInteger i = oldCount; i < newCount; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
2026-01-27 17:03:16 +08:00
//
[self.tableView layoutIfNeeded];
2026-01-26 20:36:51 +08:00
[self.tableView insertRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationNone];
}
[self updateFooterVisibility];
if (autoScroll) {
2026-01-27 17:03:16 +08:00
// 使 dispatch_async
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView layoutIfNeeded]; //
[self scrollToBottomAnimated:YES];
2026-01-26 20:36:51 +08:00
});
}
}
- (void)reloadWithMessages:(NSArray<KBAiChatMessage *> *)messages
keepOffset:(BOOL)keepOffset
scrollToBottom:(BOOL)scrollToBottom {
CGFloat oldContentHeight = self.tableView.contentSize.height;
CGFloat oldOffsetY = self.tableView.contentOffset.y;
[self.messages removeAllObjects];
if (messages.count > 0) {
for (KBAiChatMessage *message in messages) {
[self insertMessageWithTimestamp:message];
}
}
[self.tableView reloadData];
[self.tableView layoutIfNeeded];
[self updateFooterVisibility];
if (keepOffset) {
CGFloat newContentHeight = self.tableView.contentSize.height;
CGFloat delta = newContentHeight - oldContentHeight;
CGFloat offsetY = oldOffsetY + delta;
2026-01-27 17:03:16 +08:00
// 使 offset
2026-01-26 20:36:51 +08:00
[self.tableView setContentOffset:CGPointMake(0, offsetY) animated:NO];
return;
}
if (scrollToBottom) {
2026-01-27 17:03:16 +08:00
// 使
[self scrollToBottomAnimated:NO];
2026-01-26 20:36:51 +08:00
}
}
2026-01-23 21:51:37 +08:00
#pragma mark - Private Methods
///
- (void)insertMessageWithTimestamp:(KBAiChatMessage *)message {
//
if ([self shouldInsertTimestampForMessage:message]) {
KBAiChatMessage *timeMessage = [KBAiChatMessage timeMessageWithTimestamp:message.timestamp];
[self.messages addObject:timeMessage];
}
[self.messages addObject:message];
}
///
- (BOOL)shouldInsertTimestampForMessage:(KBAiChatMessage *)message {
//
if (self.messages.count == 0) {
return YES;
}
//
KBAiChatMessage *lastMessage = nil;
for (NSInteger i = self.messages.count - 1; i >= 0; i--) {
KBAiChatMessage *msg = self.messages[i];
if (msg.type != KBAiChatMessageTypeTime) {
lastMessage = msg;
break;
}
}
if (!lastMessage) {
return YES;
}
//
NSTimeInterval interval = [message.timestamp timeIntervalSinceDate:lastMessage.timestamp];
// 5
if (interval >= kTimestampInterval) {
return YES;
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *lastComponents = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
fromDate:lastMessage.timestamp];
NSDateComponents *currentComponents = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear
fromDate:message.timestamp];
return ![lastComponents isEqual:currentComponents];
}
///
- (void)reloadAndScroll {
// 使 insert reload Cell
NSInteger lastIndex = self.messages.count - 1;
if (lastIndex >= 0) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:lastIndex inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationNone];
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self scrollToBottom];
});
}
2026-01-26 20:36:51 +08:00
- (void)stopPreviousIncompleteAssistantMessageIfNeeded {
for (NSInteger i = self.messages.count - 1; i >= 0; i--) {
KBAiChatMessage *msg = self.messages[i];
if (msg.type == KBAiChatMessageTypeAssistant && !msg.isComplete) {
msg.isComplete = YES;
msg.needsTypewriterEffect = NO;
NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
KBChatAssistantMessageCell *oldCell = [self.tableView cellForRowAtIndexPath:oldIndexPath];
if ([oldCell isKindOfClass:[KBChatAssistantMessageCell class]]) {
[oldCell stopTypewriterEffect];
oldCell.messageLabel.text = msg.text;
}
break;
}
}
}
- (void)updateFooterVisibility {
BOOL canLoadMore = (self.delegate &&
[self.delegate respondsToSelector:@selector(chatTableViewDidTriggerLoadMore:)]);
self.tableView.mj_footer.hidden = !canLoadMore || self.messages.count == 0;
}
2026-01-23 21:51:37 +08:00
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.messages.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
KBAiChatMessage *message = self.messages[indexPath.row];
NSLog(@"[KBChatTableView] cellForRow: %ld, 消息类型: %ld, needsTypewriter: %d, isComplete: %d",
(long)indexPath.row, (long)message.type, message.needsTypewriterEffect, message.isComplete);
switch (message.type) {
case KBAiChatMessageTypeUser: {
KBChatUserMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:kUserCellIdentifier
forIndexPath:indexPath];
[cell configureWithMessage:message];
return cell;
}
case KBAiChatMessageTypeAssistant: {
KBChatAssistantMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:kAssistantCellIdentifier
forIndexPath:indexPath];
cell.delegate = self;
[cell configureWithMessage:message];
//
BOOL isPlaying = [indexPath isEqual:self.playingCellIndexPath];
[cell updateVoicePlayingState:isPlaying];
return cell;
}
case KBAiChatMessageTypeTime: {
KBChatTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:kTimeCellIdentifier
forIndexPath:indexPath];
[cell configureWithMessage:message];
return cell;
}
}
}
2026-01-26 20:36:51 +08:00
- (void)setDelegate:(id<KBChatTableViewDelegate>)delegate {
_delegate = delegate;
[self updateFooterVisibility];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if ([self.delegate respondsToSelector:@selector(chatTableViewDidScroll:scrollView:)]) {
[self.delegate chatTableViewDidScroll:self scrollView:scrollView];
}
}
2026-01-27 17:03:16 +08:00
///
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
withVelocity:(CGPoint)velocity
targetContentOffset:(inout CGPoint *)targetContentOffset {
CGFloat offsetY = scrollView.contentOffset.y;
CGFloat contentHeight = scrollView.contentSize.height;
CGFloat scrollViewHeight = scrollView.bounds.size.height;
//
if (contentHeight <= scrollViewHeight) {
scrollView.bounces = NO;
} else {
scrollView.bounces = YES;
//
if (velocity.y < 0) { //
CGFloat maxOffset = contentHeight - scrollViewHeight + scrollView.contentInset.bottom;
if (targetContentOffset->y > maxOffset) {
targetContentOffset->y = maxOffset;
}
}
}
}
2026-01-23 21:51:37 +08:00
#pragma mark - KBChatAssistantMessageCellDelegate
- (void)assistantMessageCell:(KBChatAssistantMessageCell *)cell
didTapVoiceButtonForMessage:(KBAiChatMessage *)message {
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
if (!indexPath) return;
//
if ([indexPath isEqual:self.playingCellIndexPath]) {
[self stopPlayingAudio];
return;
}
//
[self stopPlayingAudio];
// audioData
if (message.audioData && message.audioData.length > 0) {
[self playAudioForMessage:message atIndexPath:indexPath];
return;
}
// audioId
if (message.audioId.length > 0) {
[self loadAndPlayAudioForMessage:message atIndexPath:indexPath];
return;
}
NSLog(@"[KBChatTableView] 没有音频数据或 audioId");
}
#pragma mark - Audio Playback
- (void)loadAndPlayAudioForMessage:(KBAiChatMessage *)message atIndexPath:(NSIndexPath *)indexPath {
//
KBChatAssistantMessageCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[KBChatAssistantMessageCell class]]) {
[cell showLoadingAnimation];
}
// 50.5
[self pollAudioForMessage:message atIndexPath:indexPath retryCount:0 maxRetries:5];
}
- (void)pollAudioForMessage:(KBAiChatMessage *)message
atIndexPath:(NSIndexPath *)indexPath
retryCount:(NSInteger)retryCount
maxRetries:(NSInteger)maxRetries {
__weak typeof(self) weakSelf = self;
[self.aiVM requestAudioWithAudioId:message.audioId
completion:^(NSString *_Nullable audioURL, NSError *_Nullable error) {
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
dispatch_async(dispatch_get_main_queue(), ^{
// audioURL
if (!error && audioURL.length > 0) {
//
[strongSelf downloadAndPlayAudioFromURL:audioURL
forMessage:message
atIndexPath:indexPath];
return;
}
//
if (retryCount < maxRetries - 1) {
NSLog(@"[KBChatTableView] 音频未就绪0.5秒后重试 (%ld/%ld)",
(long)(retryCount + 1), (long)maxRetries);
// 0.5
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
[strongSelf pollAudioForMessage:message
atIndexPath:indexPath
retryCount:retryCount + 1
maxRetries:maxRetries];
});
} else {
//
KBChatAssistantMessageCell *cell = [strongSelf.tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[KBChatAssistantMessageCell class]]) {
[cell hideLoadingAnimation];
}
NSLog(@"[KBChatTableView] 音频加载失败,已重试 %ld 次", (long)maxRetries);
}
});
}];
}
- (void)downloadAndPlayAudioFromURL:(NSString *)urlString
forMessage:(KBAiChatMessage *)message
atIndexPath:(NSIndexPath *)indexPath {
NSURL *url = [NSURL URLWithString:urlString];
if (!url) {
NSLog(@"[KBChatTableView] 无效的音频 URL: %@", urlString);
//
KBChatAssistantMessageCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[KBChatAssistantMessageCell class]]) {
[cell hideLoadingAnimation];
}
return;
}
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithURL:url
completionHandler:^(NSData *_Nullable data,
NSURLResponse *_Nullable response,
NSError *_Nullable error) {
if (error || !data || data.length == 0) {
NSLog(@"[KBChatTableView] 下载音频失败: %@", error.localizedDescription ?: @"");
dispatch_async(dispatch_get_main_queue(), ^{
//
KBChatAssistantMessageCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[KBChatAssistantMessageCell class]]) {
[cell hideLoadingAnimation];
}
});
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
//
KBChatAssistantMessageCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[KBChatAssistantMessageCell class]]) {
[cell hideLoadingAnimation];
}
//
message.audioData = data;
//
NSError *playerError = nil;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:&playerError];
if (!playerError && player) {
message.audioDuration = player.duration;
}
// Cell
//
[self playAudioForMessage:message atIndexPath:indexPath];
});
}];
[task resume];
}
- (void)playAudioForMessage:(KBAiChatMessage *)message atIndexPath:(NSIndexPath *)indexPath {
if (!message.audioData || message.audioData.length == 0) {
NSLog(@"[KBChatTableView] 没有音频数据");
return;
}
//
NSError *sessionError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
[audioSession setActive:YES error:&sessionError];
if (sessionError) {
NSLog(@"[KBChatTableView] 音频会话配置失败: %@", sessionError.localizedDescription);
}
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:message.audioData error:&error];
if (error || !self.audioPlayer) {
NSLog(@"[KBChatTableView] 音频播放器初始化失败: %@", error.localizedDescription);
return;
}
self.audioPlayer.delegate = self;
self.audioPlayer.volume = 1.0; //
[self.audioPlayer prepareToPlay];
[self.audioPlayer play];
self.playingCellIndexPath = indexPath;
2026-01-26 13:51:38 +08:00
// Cell TableView
2026-01-23 21:51:37 +08:00
KBChatAssistantMessageCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[KBChatAssistantMessageCell class]]) {
2026-01-26 13:51:38 +08:00
[UIView performWithoutAnimation:^{
[cell updateVoicePlayingState:YES];
}];
2026-01-23 21:51:37 +08:00
}
}
- (void)stopPlayingAudio {
if (self.audioPlayer && self.audioPlayer.isPlaying) {
[self.audioPlayer stop];
}
if (self.playingCellIndexPath) {
KBChatAssistantMessageCell *cell = [self.tableView cellForRowAtIndexPath:self.playingCellIndexPath];
if ([cell isKindOfClass:[KBChatAssistantMessageCell class]]) {
2026-01-26 13:51:38 +08:00
// TableView
[UIView performWithoutAnimation:^{
[cell updateVoicePlayingState:NO];
}];
2026-01-23 21:51:37 +08:00
}
self.playingCellIndexPath = nil;
}
}
#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[self stopPlayingAudio];
}
@end