Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

iphone - Sound overlapping with multiple button presses

When I press a button, then press another one, the sounds overlap. How can I fix that so the first sound stops when another one is pressed?

 - (void)playOnce:(NSString *)aSound {

NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio setDelegate: self];
[theAudio setNumberOfLoops:0];
[theAudio setVolume:1.0];
[theAudio play];    
 }

- (void)playLooped:(NSString *)aSound {

NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio setDelegate: self];
// loop indefinitely
[theAudio setNumberOfLoops:-1];
[theAudio setVolume:1.0];
[theAudio play];
[theAudio release];


    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Declare your AVAudioPlayer in the header the viewController ( don't alloc a new one each time you play a sound). That way you will have a pointer you can use in a StopAudio method.

@interface myViewController : UIViewController <AVAudioPlayerDelegate> { 
    AVAudioPlayer *theAudio;
}
@property (nonatomic, retain) AVAudioPlayer *theAudio;
@end


@implementation myViewController
@synthesize theAudio;
- (void)dealloc {
    [theAudio release];
}
@end



- (void)playOnce:(NSString *)aSound {
    NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
    if(!theAudio){
        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL];
    }
    [theAudio setDelegate: self];
    [theAudio setNumberOfLoops:0];
    [theAudio setVolume:1.0];
    [theAudio play];
}

- (void)playLooped:(NSString *)aSound {
    NSString *path = [[NSBundle mainBundle] pathForResource:aSound ofType:@"caf"];
    if(!theAudio){
        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL];
    }
    [theAudio setDelegate: self];
    // loop indefinitely
    [theAudio setNumberOfLoops:-1];
    [theAudio setVolume:1.0];
    [theAudio play];
}

- (void)stopAudio {
    [theAudio stop];
    [theAudio setCurrentTime:0];
}

also be sure to read the Apple Docs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...