我试图在我的iPhone游戏中播放背景歌曲,并且使用AVFoundation框架和AVPlayerItem也有声音效果。我在互联网上搜索了AVPlayerItem和AVPlayer的帮助,但我只能找到关于AVAudioPlayer的东西。使用AVPlayer播放多个声音的问题(NOT AVAudioPlayer)
背景歌曲播放很好,但是当人物跳跃,我有2个问题:
1)在初始跳([播放器播放]跳法里),跳音效中断背景音乐。
2)如果我尝试再次跳,与错误的游戏崩溃“AVPlayerItem不能与AVPlayer的多个实例相关联的”
我的教授告诉我,为每个声音创建AVPlayer的新实例我想玩,所以我很困惑。
我正在做数据驱动的设计,所以我的声音文件列在.txt中,然后加载到NSDictionary。
这里是我的代码:
- (void) storeSoundNamed:(NSString *) soundName
withFileName:(NSString *) soundFileName
{
NSURL *assetURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:soundName ofType:soundFileName]];
AVURLAsset *mAsset = [[AVURLAsset alloc] initWithURL:assetURL options:nil];
AVPlayerItem *mPlayerItem = [AVPlayerItem playerItemWithAsset:mAsset];
[soundDictionary setObject:mPlayerItem forKey:soundName];
NSLog(@"Sound added.");
}
- (void) playSound:(NSString *) soundName
{
// from .h: @property AVPlayer *mPlayer;
// from .m: @synthesize mPlayer = _mPlayer;
_mPlayer = [[AVPlayer alloc] initWithPlayerItem:[soundDictionary valueForKey:soundName]];
[_mPlayer play];
NSLog(@"Playing sound.");
}
如果我提出从第二种方法这条线进入第一:
_mPlayer = [[AVPlayer alloc] initWithPlayerItem:[soundDictionary valueForKey:soundName]];
游戏不死机,背景歌曲将完全发挥,但即使控制台显示“播放声音”,跳跃音效也不会播放。在每次跳跃。
谢谢