我試圖在我的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]];
遊戲不死機,背景歌曲將完全發揮,但即使控制檯顯示「播放聲音」,跳躍音效也不會播放。在每次跳躍。
謝謝