How to stop a audio SKAction?

前端 未结 2 1354
有刺的猬
有刺的猬 2020-12-07 00:48

Goal: I want to present a new scene:

[self.scene.view presentScene:level2 transition:reveal];

and end the current background music in orde

2条回答
  •  有刺的猬
    2020-12-07 01:42

    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 
    
    @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.

提交回复
热议问题