2012-06-04 49 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."); 
}