2016-12-13 24 views
0

我有一种基于sprite kit游戏的播放环境声音的方法,但我想知道是否有更好的方法。我已经看到了类型中的环境声音函数,但它似乎是框架使用的东西,而不是框架用户的东西。在sprite kit iOS 10 Xcode 8中播放环境声音比这更好吗?

这是我目前在做什么

- (void) playAmbientSound { 

    [self runAction:self.pAmbientSound completion:^{ 
     [self playAmbientSound]; 
    }]; 
} 



- (void) initSounds { 
    // Avatar swim sound 
    self.pSwimSound = [SKAction playSoundFileNamed:@"swim-sound.m4a" waitForCompletion:NO]; 

    // Animation sound 
    self.pAmbientSound = [SKAction playSoundFileNamed:@"ambient-final.mp3" waitForCompletion:YES]; 
    // Do the Sound in a loop 
    [self playAmbientSound]; 

} 
+0

更好地使用AVAudioPlayer来播放环境声音。 – GeneCode

+0

关于文件扩展还有另外一点,我读了一些扩展没有像AVAudioPlayer一样使用.m4a。试图给不同的扩展。 – Mina

回答

2

SKAudioNode是让周围的音频,游戏的最佳方式。它建立在AVFoundation之上,可以与SKAction一起使用,以改变声音的音量或提供3D位置声音。另外SKScene有一个audioEngine属性,它是AVAudioEngine类型。这将允许您一次管理所有音频节点,以便在需要停止所有音频或更改所有内容的整体音量的情况下使用。

3

您可以使用AVAudioPlayer。

在Objective-C的样本:

添加audioPlayer.h文件

@property (strong, nonatomic)AVAudioPlayer *audioPlayer; 

然后在.m文件中使用这样的:

NSString *path = [NSString stringWithFormat:@"%@/background.mp3",[[NSBundle mainBundle] resourcePath]]; 
NSURL *fileURL = [NSURL fileURLWithPath:path]; 

_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil]; 
_audioPlayer.numberOfLoops = -1; //Infinite 
[_audioPlayer prepareToPlay]; 
[_audioPlayer play]; 

而且在斯威夫特3是这样的:

func playMusic() { 
    let path = Bundle.main.path(forResource: "background", ofType: "mp3") 
    let fileURL = URL(fileURLWithPath: path!) 
    do { 
     audioPlayer = try AVAudioPlayer(contentsOf: fileURL) 
    } catch { 
     print("error play music") 
    } 
    audioPlayer.numberOfLoops = -1 //Infinite 
    audioPlayer.prepareToPlay() 
    audioPlayer.play() 
} 

为无限循环播放你需要设置numberOfLoops等于-1