How to stop a audio SKAction?

痞子三分冷 提交于 2019-11-28 01:51:06

You can't stop audio from playing when run from SKAction. You will need another engine to run your background music.
Try AVAudioPlayer - it is really easy and straightforward to use. Something like this will work:

First import header and add new property to your scene or view controller:

#import <AVFoundation/AVFoundation.h>

@interface AudioPlayerViewController : UIViewController {

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;

}

After this in viewDidLoad or in didMoveToView method of scene add following code:

- (void)viewDidLoad {
    [super viewDidLoad];

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

    NSError *error;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    self.audioPlayer.numberOfLoops = -1;

    if (!self.audioPlayer)
        NSLog([error localizedDescription]);                
    else 
        [self.audioPlayer play];

}

Each time you need your music to stop, just call [self.audioPlayer stop];

When you need new music to play, put a new player into the property initialized with your new music piece.

Hope this helps.

Now you can stop playing sound action by assigning key string for it then using removeActionForKey later

Sorry, this is Swift. But it can be ported to Obj-C.

let action: SKAction = SKAction.playSoundFileNamed("sounds/boom.wav", waitForCompletion: true)
self.runAction(action, withKey:"die-sound")
// later you do:
self.removeActionForKey("die-sound")

I have tested successful

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!