Play/Pause with the same button [AVAudioPlayer]

前端 未结 2 1023
天命终不由人
天命终不由人 2020-12-31 14:21

How can I play a sound with an IBAction by pressing on a UIbutton once and pause it by pressing the button again using AVAudioPlayer?

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-31 15:19

    Keep your audioPlayer instance ready to play using the below method.

    /*
     Prepares the audio file to play.
     */
    -(void) initWithAudioPath:(NSString *) audioPath {
        // Converts the sound's file path to an NSURL object
        NSURL *audioPathURL = [[NSURL alloc] initFileURLWithPath:audioPath];
    
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioPathURL error:nil];
        audioPlayer.delegate = self;
    
        [audioPlayer prepareToPlay];
    
        [audioPathURL release];
    }
    
    -(void) pausePlaybackForPlayer:(AVAudioPlayer *) player {
        [player pause];
    }
    
    -(void) startPlaybackForPlayer:(AVAudioPlayer *) player {
        if (![player play]) {
            NSLog(@"Could not play %@\n", player.url);
        }
    }
    
    - (IBAction)Beat {
        if (audioPlayer.playing == NO) {
            // Audio player is not playing.
            // Set the button title here to "stop"...
            [self startPlaybackForPlayer:audioPlayer];
        }else {
            // Audio player is playing.
            // Set the button title here to "play"...
            [self pausePlaybackForPlayer:audioPlayer];
        }
    
    }
    

提交回复
热议问题