Skip to main content
 首页 » 编程设计

objective-c之由于未捕获的异常 'NSInvalidArgumentException'终止了应用程序,原因: '*** -[NSURL initFileURLWithPath:]: nil string parameter'

2025年05月04日135开发

我正在尝试随机播放4个音频文件。这是代码

  // randomize the playback on the setShot files 
   int randomNumber = arc4random() % 4 + 1; 
   NSString *tmpFileName = [[NSString alloc] initWithFormat:@"SetShot%d", randomNumber]; 
   NSString *fileName = [[NSBundle mainBundle] pathForResource:tmpFileName ofType:@"aif"]; 
   SystemSoundID soundID; 
   AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:fileName], &soundID); 
   AudioServicesPlaySystemSound (soundID); 

我在模拟器上未在设备上遇到上述崩溃。我是编码新手。
感谢你的帮助。

声音文件从SetShot01到SetShot04

具有5.1.1的设备上的ARC-armv6,armv7 xcode 4.3.2

请您参考如下方法:

您的tmpFileName文件可能不存在于主 bundle 包中。这将导致网址为nil。这是因为您说的文件名是SetShot0 [1-4],而正在创建的字符串是SetShot [1-4]。更改

NSString *tmpFileName = [[NSString alloc] initWithFormat:@"SetShot%d", randomNumber]; 

阅读为
 NSString *tmpFileName = [[NSString alloc] initWithFormat:@"SetShot0%d", randomNumber];