背景音乐游戏正确但停止给出例外

时间:2014-08-07 12:46:56

标签: ios objective-c xcode avfoundation

我试图在后台为我的游戏播放一些音乐。除非用户在设置中将其关闭,否则音乐将永远不会停止。音乐将始终在每个视图的背景中播放,并且不会暂停或等等。

出于这个原因,我为我的背景音乐制作了一个单身课程。但是当我按下"停止播放音乐"时,应用程序会断点异常(我没有看到一个,所以我不知道什么是错的。)

音乐仍然停止,但有些不对劲,我不知道是什么。在单件类中制作它是正确的,还是需要以其他方式解决这个问题?

以下是异常发生时的屏幕截图: Image about the exception

以下是我的单身人士课程的代码:

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

@interface Music : NSObject

@property AVAudioPlayer *player;

- (void)stop;
- (void)play;

+ (Music *)sharedInstance;

@end

#import "Music.h"

@implementation Music

+ (Music *)sharedInstance {

    static Music *sharedInstance;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken,^{

        sharedInstance = [[Music alloc] init];
    });

    return sharedInstance;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                             pathForResource:@"water_2"
                                             ofType:@"wav"]];

        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        self.player.numberOfLoops = -1;
    }

    return self;
}

- (void)stop{
    [self.player stop];
}

- (void)play{
    [self.player play];
}

1 个答案:

答案 0 :(得分:0)

我会切换你的代码,我会使用IBAction而不是void stop and void play

-(IBAction)stop {

[player stop];

}

-(IBAction)play {

[player play];

}