ios - spritekit 游戏中的音效开/关

标签 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

最佳答案

要为您的游戏添加音效,我建议使用 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];
    }
}

关于ios - spritekit 游戏中的音效开/关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25584474/

相关文章:

ios - UITableViewCell 中的第三个标签打乱了文本

iOS - 允许我的应用程序在锁定屏幕上显示信息吗?

ios - 应用程序未在设备中自动启动并在 xcode 上出现错误

ios - 实现文件中的 Objective-C 代码结构

objective-c - 如何在 iPhone 中执行延迟测试

objective-c - Cocoa 与核心数据的绑定(bind)未更新所有列

android - 移动网络浏览器上的 Thaana 字体

ios - UIButton 标签在选择时不尊重先前动画的完成处理程序设置的文本

objective-c - 自 OSX 10.8 起屏幕保护程序崩溃

iphone - 模型类中的 NSXMLParser 没有给我结果