AVAudioPlayer将应用程序保存在加载屏幕中

时间:2014-12-12 02:39:15

标签: ios objective-c sprite-kit avaudioplayer

当我使用此代码在我的第一个场景中播放我的音乐时,该应用程序会显示加载屏幕,但随后会停留在那里并且不会进入我的主菜单或其他任何内容。有什么建议吗?

        NSError *error;
    NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"POL-parallel-fields-short" withExtension:@"mp3"];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
    [player setVolume:0.1];
    player.numberOfLoops = -1;
    [player prepareToPlay];

    SKAction*   playAction = [SKAction runBlock:^{
        [player play];
        }];
    SKAction *playMusic = [SKAction repeatActionForever:playAction];

    [self runAction:playMusic];

1 个答案:

答案 0 :(得分:0)

我建议创建MusicHelper实例。

//MusicHelper.m

@interface MusicHelper()
@property (nonatomic) AVAudioPlayer * backgroundMusicPlayer;
@end

@implementation MusicHelper

+ (instancetype)sharedInstance {
    static dispatch_once_t pred;
    static MusicHelper * _sharedInstance;
    dispatch_once(&pred, ^{ _sharedInstance = [[self alloc] init]; });
    return _sharedInstance;
}

- (void)playBackgroundMusic:(NSString *)filename {
    NSError *error;
    NSURL * backgroundMusicURL = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
    self.backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
    self.backgroundMusicPlayer.numberOfLoops = -1;
    [self.backgroundMusicPlayer prepareToPlay];
    [self.backgroundMusicPlayer play];
}

- (void)pauseBackgroundMusic
{
    [self.backgroundMusicPlayer pause];
}

@end

//MusicHelper.h

#import <Foundation/Foundation.h>
@import AVFoundation;

@interface MusicHelper : NSObject

+ (instancetype)sharedInstance;
- (void)playBackgroundMusic:(NSString *)filename;
- (void)pauseBackgroundMusic;

@end

你可以在任何场景中这样打电话。

[[MusicHelper sharedInstance] playBackgroundMusic:@"yourMusic.mp3"]; //Play
[[MusicHelper sharedInstance] pauseBackgroundMusic]; //Stop