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