Sound overlapping with multiple button presses

前端 未结 6 1554
野的像风
野的像风 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:50

    You will need to utizilize a BOOL value to get this to work properly.

    in your .m file BEFORE @implementation put this:

    static BOOL soundIsPlaying = NO;
    

    Then your IBAction needs to look something like this:

    - (IBAction)play {
        if (soundIsPlaying == YES) {
            [theAudio release];
            soundIsPlaying = NO;
    
        }
    
        else if (soundIsPlaying == NO) {
            NSString *path = [[NSBundle mainBundle] pathForResource:@"SOUNDFILENAME" ofType:@"wav"];
            theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
            theAudio.delegate = self;
            theAudio.volume = 1.0;
            theAudio.numberOfLoops = 0;
            [theAudio play];
            soundIsPlaying = YES;
    
        }   
    }
    

    thats honestly about it. It will stop sounds when another button is pressed.

提交回复
热议问题