2014-08-30 43 views
1

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

//.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 
+0

您可以用[_backgroundAudioPlayer暂停]暂停音乐,或用[_backgroundAudioPlayer停止]停止音乐。 – 0x141E 2014-08-30 16:43:56

+0

我知道这个戏,暂停和停止,但我想打开/关闭所有我的3种声音同时停止? – anjani 2014-08-30 17:06:01

+0

您是否想要在游戏或音效中播放背景音乐? – 0x141E 2014-08-30 18:30:24

回答

1

要将声音效果添加到您的游戏中,我建议使用playSoundFileNamed SKAction而不是AVAudioPlayer。下面是如何做到这一点的例子:

@property BOOL playSounds; 

// Define action to play a sound effect 
_playJumpSound = [SKAction [email protected]"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]; 
    } 
} 
+0

你试过这个吗? – 0x141E 2014-09-01 06:45:49

+0

它的工作正常,但我担心打开/关闭按钮,而我想打开播放所有声音和关闭按钮停止所有声音 – anjani 2014-09-01 07:35:42

+0

请参阅我编辑的答案。 – 0x141E 2014-09-01 07:40:54