2011-07-09 30 views
9

Làm cách nào để phát âm thanh với IBAction bằng cách nhấn vào một lần UIbutton một lần và tạm dừng bằng cách nhấn lại nút bằng cách sử dụng AVAudioPlayer? Ngoài ra tôi muốn thay đổi trạng thái của số đó UIButton khi âm thanh đang phát và khi không.Phát/Tạm dừng bằng cùng một nút [AVAudioPlayer]

Dưới đây là mã của tôi:

- (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]; 
    } 
} 

Trả lời

13

Đây là phương pháp đơn giản sử dụng BOOL Biến.

Đặt playing = NO trong viewDidLoad.

-(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; 
    } 
} 
3

Giữ dụ Audioplayer của bạn đã sẵn sàng để chơi bằng cách sử dụng phương pháp dưới đây.

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

} 
Các vấn đề liên quan