2013-12-12 271 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