You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AVPlayer仅播放NSMutableArray中最后一个链接的问题求助

问题分析与解决方案

问题定位

核心问题是解析本地m3u8文件时,除最后一个URL外,其余URL字符串大概率包含不可见的空白字符(如回车符\r),导致NSURL URLWithString:无法生成有效URL对象,最终AVPlayer无法播放。

最后一个链接能正常播放的原因:m3u8文件的最后一行通常没有多余换行符,而前面的行因采用\n拆分Windows风格的\r\n换行,字符串末尾会残留\r字符,这些非法字符会导致URL解析失败。

验证方法

在播放代码前添加以下日志,验证URL有效性:

NSString *urlStr = [movieURL objectAtIndex:0]; // 替换为0-8测试前面的链接
NSLog(@"原始URL字符串: %@", urlStr);
NSLog(@"字符串长度: %lu", (unsigned long)urlStr.length);
NSURL *url = [NSURL URLWithString:urlStr];
NSLog(@"生成的NSURL: %@", url); // 若输出为null,说明字符串存在非法字符

解决方案

修改sortM3UFile方法,对每行字符串做首尾空白字符清理,同时过滤空行:

- (void)sortM3UFile {
    for (NSString *line in tempArray) {
        NSString *trimmedLine = [line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if (trimmedLine.length == 0) continue; // 跳过空行
        
        if ([trimmedLine containsString:@"://"]) {
            [movieURL addObject:trimmedLine];
        }
        
        if ([trimmedLine containsString:@"#EXTINF:-1 ,"]) {
            // 可选:剥离标题前缀,只保留纯标题文本
            NSString *pureTitle = [trimmedLine stringByReplacingOccurrencesOfString:@"#EXTINF:-1 ," withString:@""];
            [movieTitle addObject:pureTitle];
        }
    }
}

额外优化建议

  1. 读取文件时添加错误处理,避免静默失败:
NSError *error = nil;
NSString *fileContents1 = [NSString stringWithContentsOfFile:addPath encoding:NSUTF8StringEncoding error:&error];
if (!fileContents1) {
    NSLog(@"读取m3u8文件失败: %@", error.localizedDescription);
    return;
}
  1. 播放前先校验URL有效性:
NSString *urlStr = [movieURL objectAtIndex:index];
NSURL *url = [NSURL URLWithString:urlStr];
if (!url) {
    NSLog(@"无效URL: %@", urlStr);
    return;
}
AVPlayer *player = [AVPlayer playerWithURL:url];
// 后续播放代码...

内容的提问来源于stack exchange,提问作者aLFaRSi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 19:37:43