我正在为 AVAudioPlayer 使用单例,效果很好。
我希望在初始化播放器之前添加一个检查,如果播放器已经在播放某些内容,则停止播放器。
我添加了这段代码:
SoundPlayer *player = [SoundPlayer sharedInstance];
if([player isPlaying]){
[player stop];
}
但是它给了我一个EXE_BAD_ACCESS就if([player isPlaying])
行了。
2个问题:
- 如果这是一个单例并且我要找回同一个玩家,那么为什么它不自己停止呢?
- 为什么我会收到错误消息?
这是完整的代码
#import "SoundPlayer.h"
@implementation SoundPlayer
@synthesize helpMode;
static SoundPlayer *sharedInstance = nil;
+ (SoundPlayer *)sharedInstance {
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
return sharedInstance;
}
+(BOOL)playSound:(NSURL*)url{
NSError *error;
SoundPlayer *player = [SoundPlayer sharedInstance];
if([player isPlaying]){
[player stop];
}
player = [[SoundPlayer sharedInstance] initWithContentsOfURL:url error:&error];
[player play];
if (player == nil){
NSLog(@"error %@ \n for file %@",[error description],[url path]);
return NO;
}else {
if (![player helpMode]) {
[player play];
}else{
NSLog(@"help mode");
}
}
return YES;
}
-(void)stopSound{
if ([self isPlaying]) {
[self stop];
}
}
@end