我正在使用此功能在我的iPhone应用程序上播放声音。问题是声音没有播放。该功能正常工作并正确读取文件路径,我没有收到任何错误,但声音没有播放
-(void) playSound : (NSString *) fName; {
if ([audioPlayer isPlaying]) {
[audioPlayer stop];
}
audioPlayer.volume = 1.0;
soundpath = [NSString stringWithFormat:@"sounds/%@", fName];
soundFilePath = [[NSBundle mainBundle] pathForResource:soundpath ofType: @"mp3"];
soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil){
}
else {
[audioPlayer play];
if ([audioPlayer isPlaying]) {
NSLog(@"%@", @"run");
}
}
}
答案 0 :(得分:5)
尝试添加此内容:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error: nil];
UInt32 route = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(route), &route);
我有类似的问题,并在调用游戏之前添加了它,它解决了我的问题。