Objective c 使用AVPlayer(非AVAudioPlayer)播放多个声音时出现问题
我正在尝试在我的iPhone游戏中播放一首背景歌曲,并使用AVFoundation框架和AVPlayerItem实现音效。我在互联网上搜索了AVPlayerItem和AVPlayer的帮助,但我只找到了关于AVAudioPlayer的资料 背景曲播放得很好,但当角色跳跃时,我有两个问题: 1) 在初始跳跃([player play]inside jump method)时,跳跃音效会中断背景音乐 2) 如果我再次尝试跳转,游戏将崩溃,错误为“AVPlayerItem不能与AVPlayer的多个实例关联” 我的教授告诉我为我想播放的每个声音创建一个新的AVPlayer实例,所以我很困惑 我正在做数据驱动的设计,所以我的声音文件会以.txt格式列出,然后加载到NSDictionary中 这是我的密码:Objective c 使用AVPlayer(非AVAudioPlayer)播放多个声音时出现问题,objective-c,xcode4,avfoundation,Objective C,Xcode4,Avfoundation,我正在尝试在我的iPhone游戏中播放一首背景歌曲,并使用AVFoundation框架和AVPlayerItem实现音效。我在互联网上搜索了AVPlayerItem和AVPlayer的帮助,但我只找到了关于AVAudioPlayer的资料 背景曲播放得很好,但当角色跳跃时,我有两个问题: 1) 在初始跳跃([player play]inside jump method)时,跳跃音效会中断背景音乐 2) 如果我再次尝试跳转,游戏将崩溃,错误为“AVPlayerItem不能与AVPlayer的多个实
- (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]];
游戏不会崩溃,背景歌曲也会完美播放,但跳跃音效不会播放,即使游戏机在每次跳跃时都显示“播放音效”
谢谢我想出来了
错误信息告诉我我需要知道的一切:每个AVPlayerItem不能有一个以上的AVPlayer,这与我所学的相反
无论如何,我没有将AVPlayerItems存储在soundDictionary中,而是将AVURLAssets存储在soundDictionary中,soundName作为每个资产的键。然后,每当我想播放声音时,我就创建了一个新的AVPlayerItem和AVPlayer
另一个问题是ARC。我无法跟踪每个不同项目的AVPlayerItem,因此我必须制作一个NSMutableArray来存储AVPlayerItem和AVPlayer
以下是固定代码:
- (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];
[_soundDictionary setObject:mAsset forKey:soundName];
NSLog(@"Sound added.");
}
- (void) playSound:(NSString *) soundName
{
// beforehand: @synthesize soundArray;
// in init: self.soundArray = [[NSMutableArray alloc] init];
AVPlayerItem *mPlayerItem = [AVPlayerItem playerItemWithAsset:[_soundDictionary valueForKey:soundName]];
[self.soundArray addObject:mPlayerItem];
AVPlayer *tempPlayer = [[AVPlayer alloc] initWithPlayerItem:mPlayerItem];
[self.soundArray addObject:tempPlayer];
[tempPlayer play];
NSLog(@"Playing Sound.");
}