Sound overlapping with multiple button presses

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

    You can probably do something like the following:

        (void) playLooped: (NSString * ) aSound {
            NSString * path = [[NSBundle mainBundle] pathForResource: aSound ofType: @"caf"];
    
        //stop audio player from playing so the sound don't overlap
        if([theAudio isPlaying])
        {
            [theAudio stop]; //try this instead of stopAudio
    
        }
    
        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];
    }
    

提交回复
热议问题