Sound overlapping with multiple button presses

前端 未结 6 1565
野的像风
野的像风 2020-11-29 13:56

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         


        
6条回答
  •  余生分开走
    2020-11-29 14:59

    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  { 
        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

提交回复
热议问题