2014-08-30 73 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