2013-12-12 266 views
0

我有一個音板應用程序播放聲音,應該播放音樂,如果你點擊按鈕,然後它暫停,但它不會暫停它只停止音樂。 一旦音樂結束,按鈕保持選中狀態。播放和暫停功能

我的代碼是;

- (IBAction)aint:(id)sender { 
UIButton *aint = (UIButton *)sender; 

aint.selected = !aint.selected; 

if(aint.selected) 
{ 
    // Play 
    NSString *path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"]; 
    theAudio2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:NULL]; 
    theAudio2.delegate = self; 
    theAudio2.numberOfLoops = 0; 
    [theAudio2 play]; 
    [[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"]; 
} 
else 
{ 
    // Pause 
    [theAudio2 pause]; 
} 
} 

而且我聲明瞭Audio2和AVAudioPlayer。

回答

1

試試這個預期它會工作 -

- (void)viewDidLoad 
    { 
     [super viewDidLoad]; 

     NSString *path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"mp3"]; 
     theAudio2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path2] error:NULL]; 
     theAudio2.delegate = self; 
     theAudio2.numberOfLoops = 0; 
    } 

- (IBAction)aint:(id)sender 
    { 
     UIButton *aint = (UIButton *)sender; 
     aint.selected = !aint.selected; 

     if(aint.selected) 
     { 
     // Play 
     [theAudio2 play]; 
     [[NSUserDefaults standardUserDefaults] setObject:@"-" forKey:@"music"]; 
     } 
     else 
     { 
     // Pause 
     [theAudio2 pause]; 
     } 
    } 

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 
    { 
     playerBtn.selected = NO; 
    } 
+0

的'playerBtn'被人'aint'是,它不會工作說'使用未聲明的標識符aint'的。 – user3089637

+0

在你的.h文件中聲明PlayerBtn,並將它連接到Xib文件中的UIButton,然後你就可以使它工作。 – Ilyas

+0

給我你的郵件ID我可以郵寄給你工作代碼。 – Ilyas