请注意Stephen下面的精彩提示:AVAudioPlayer(出于某种原因!)在正常工作时抛出异常;它可能根本没有崩溃。
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mp3"];
AVAudioPlayer *snd = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
NSLog(@"sound = nil? %d",snd == nil); // 0
NSLog(@"file = %@",snd.url.filePathURL.lastPathComponent); //test.mp3
NSLog(@"duration %f",snd.duration); //96.213333
以上行后:
1)snd不是零 - 那没关系
2)snd.url.filePathURL.lastPathComponent返回正确的文件名(test.mp3), - 那没关系
3)持续时间是96.213333 - 那没关系
因此对象存在且声音已加载(持续时间正常)
然后我做
[snd play]
它崩溃了
如果我这样做
[snd prepareToPlay]
它也崩溃了:(
任何人都知道为什么会崩溃?
答案 0 :(得分:1)
试试这段代码。它正在工作,我在我的代码中使用过 它已经在Xcode 5上进行了测试并且有效:
NSURL* url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"mp3"];
NSAssert(url, @"URL is valid.");
NSError* error = nil;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
if(!audioPlayer)
{
NSLog(@"Error creating player: %@", error);
}
else
{
[audioPlayer play];
}