2012-06-04 57 views
0

我试图在我的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]]; 

游戏不死机,背景歌曲将完全发挥,但即使控制台显示“播放声音”,跳跃音效也不会播放。在每次跳跃。

谢谢

回答

0

我想通了。

错误信息告诉我我需要知道的一切:每个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."); 
}