Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...