我初始化一个AVAudioPlayer实例:
NSString* path = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"wav"];
AVAudioPlayer* player =[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil]; //Returned object not nil, indicating that the file has loaded successfully
BOOL b = [player prepareToPlay]; //returns TRUE
BOOL b2 = [player play];
//returns TRUE, goes immediately to the next line since asynchronous
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]; //wait 1 sec
printf("%10.4f\n",player.duration); //duration is 2s
printf("%10.4f\n",player.currentTime); //position remains 0
/* There is no sound output, player is also stuck since position==0 */
有谁知道为什么AVAudioPlayer没有响应?在初始化,播放音频播放器时,我有什么东西可以忽略吗? Boilerplate代码可能?
我在iPhone模拟器上运行它。此外,AudioServicesPlaySystemSound()适用于同一个文件,这令人费解,但这表明声音播放也可以与AVAudioPlayer一起使用。
答案 0 :(得分:2)
我有2个快速建议:
检查该路径是否实际为您提供数据。使用[[NSData alloc] initWithContentsOfFile:path]分配NSData对象并在调试器中检查它以查看您是否实际加载了该wav文件。
我在这里写了一个使用AVAudioPlayer的示例项目:AVAudioPlayer Example。由于代码与您的代码几乎相同,我唯一可以想象的是您的数据存在问题。
检查一下,看看它能不能带你到任何地方!
答案 1 :(得分:2)
我刚遇到类似的问题。我不确定它是否是相同的解决方案,但我的应用程序通过iPhone录制音频,然后将其播放回用户。
我以为我通过告诉我的音频会话它会记录数据来做正确的事情,所以我做了以下事情:
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
使用此设置播放在模拟器上工作,但在设备上没有... .... didFinishPlaying事件从未被提升过。
我意识到我不需要音频播放开始正常工作后删除了这一行。现在我只需要弄清楚为什么它如此安静:)
保