在我的应用程序中,只要应用程序开始播放无限循环的背景声音,我就会启动 AVAudioPlayer。此背景声音应在应用程序打开的整个过程中播放。
当我打开应用程序时,背景声音正确启动,但是当我创建另一个播放器并启动另一个声音(例如当我触摸显示屏时)时,第二个声音开始播放并且背景声音由于某种原因停止。
// This should start the background sound. _audioPlayer is declared in the header file.
_audioPlayer = [[AudioPlayer alloc] init];
[_audioPlayer soundPlay:@"/rainforestambience.wav" withLoops:-1];
// Starts another sound later.
AudioPlayer *monkeyPlayer = [[AudioPlayer alloc] init];
[monkeyPlayer soundPlay:@"/jungle1.wav" withLoops:1];
// Play function in my AudioPlayer class.
AVAudioPlayer *player;
- (void) soundPlay:(NSString *)filePath withLoops: (int)loops
{
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:filePath];
NSLog(@"Path to play: %@", resourcePath);
NSError* err;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
player.numberOfLoops = loops;
[player prepareToPlay];
if(err) {
NSLog(@"Failed with reason: %@", [err localizedDescription]);
} else {
[player play];
}
}
编辑:通过更改我的 AudioPlayer 类中的一行来修复它。
而不是拥有
AVAudioPlayer *player;
在 AudioPlayer.m 文件中,我将变量移动到声明空间的头文件中。现在它可以按预期完美运行。:)