簡體   English   中英

使用相同的按鈕播放/暫停 [AVAudioPlayer]

[英]Play/Pause with the same button [AVAudioPlayer]

如何通過按一次UIbutton並使用AVAudioPlayer再次按下按鈕來暫停它來使用IBAction播放聲音? 另外,我想在播放聲音和不播放聲音時更改 UIButton 的UIButton

這是我的代碼:

- (IBAction)Beat
{
    if ([Media2 isPlaying])
    {
        [Media2 pause];
        [Button17 setSelected:NO];
    }

    else
    {
        Path = [[NSBundle mainBundle] pathForResource:@"Beat" ofType:@"mp3"];
        AVAudioPlayer *Media2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
        [Media2 setDelegate:self];
        [Media2 play];
        [Button17 setSelected:YES];
    }
}

這是使用BOOL變量的簡單方法。

viewDidLoad中設置playing = NO

-(void)PlayStop{    
    if (playing==NO) {
        // Init audio with playback capability
        [play setBackgroundImage:[UIImage imageNamed:@"hmpause.png"] forState:UIControlStateNormal];

        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:______ error:&err];
        [audioPlayer prepareToPlay];

        audioPlayer.delegate=self;
        [audioPlayer play];

        playing=YES;
    }
    else if(playing==YES){
        [play setBackgroundImage:[UIImage imageNamed:@"Audioplay.png"] forState:UIControlStateNormal];

        [audioPlayer pause];

        playing=NO;
    }
}

使用以下方法讓您的 audioPlayer 實例准備好播放。

/*
 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];
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM