spritekit游戏中的声音效果开/关

时间:2014-08-30 16:21:40

标签: ios objective-c iphone ios7 sprite-kit

在gameScene.m中我们如何在玩游戏的同时使用skspritenode制作开/关音乐,使用下面的代码我可以完美地播放声音,但我希望每当用户想要开启或关闭游戏中的声音时开启/关闭玩自己的ipad。

//.h file
#import <SpriteKit/SpriteKit.h>
@interface MyScene : SKScene


//.m file
#import "MyScene.h"
#import <AVFoundation/AVAudioPlayer.h>
@interface MyScene() <SKPhysicsContactDelegate>
@end

@import AVFoundation;

@implementation MyScene 
{AVAudioPlayer *_AudioPlayer;}



-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (_gameLayer.speed > 0) {
    //for flying plane
    _playerPlane.physicsBody.velocity = CGVectorMake(0, 0);
    [_playerPlane.physicsBody applyImpulse:CGVectorMake(0, 14)];
    [self jumpsound]; 
}
-(void)didBeginContact:(SKPhysicsContact *)contact{
       _gameLayer.speed = 0;
        [self removeAllActions];
       skspritenodeGameOver.hidden = NO;
       [self hitSound];}

- (void)jumpsound
{
NSURL *file = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"jump" ofType:@"wav"]];
_AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];

[_AudioPlayer setVolume:0.5];
[_AudioPlayer play];  
}

- (void)hitsound
{
  NSURL *file = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"jump" ofType:@"wav"]];
_AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];

[_AudioPlayer setVolume:0.5];
[_AudioPlayer play];  
}
@end

1 个答案:

答案 0 :(得分:1)

要为游戏添加声音效果,我建议使用playSoundFileNamed SKAction而不是AVAudioPlayer。以下是如何执行此操作的示例:

@property BOOL playSounds;

// Define action to play a sound effect
_playJumpSound = [SKAction playSoundFileNamed@"jump.wav" waitForCompletion:NO];

// Play sound effect only if playSounds is set
if (_playSounds) {
  [self runAction:_playJumpSound];
}

编辑:向方法添加声音。声音仅在_playSounds == YES。

时播放
- (void) playJumpSound
{
    if (_playSounds) {
        [self runAction:_playJumpSound];
    }
}

- (void) playHitSound
{
    if (_playSounds) {
        [self runAction:_playHitSound];
    }
}
相关问题