2011-07-20 47 views
1

我是一个n00b和寻求帮助。在相同的按钮,我想停止和播放声音如何使自定义UIButton切换声音开/关

- (void)addButtonSpeaker { 
UIButton *buttonSpeaker = [UIButton buttonWithType:UIButtonTypeCustom]; 
          [buttonSpeaker setFrame:CGRectMake(650, 930, 63, 66)]; 
[buttonSpeaker setBackgroundImage:[UIImage imageNamed:@"buttonLesen.png"] 
         forState:UIControlStateNormal]; 
[buttonSpeaker addTarget:self action:@selector(playAudio) 
     forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:buttonSpeaker]; 
} 

- (void)playAudio { 
NSString *path = [[NSBundle mainBundle] pathForResource:@"Vorwort" ofType:@"mp3"]; 
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL  
fileURLWithPath:path] error:NULL]; 
self.audioPlayer = theAudio; 
[theAudio release]; 
[theAudio play]; 
} 

现在我可以用下面的代码开始音效档。 也许我在寻找错误的东西,但我无法在网上找到适当的信息。

如果有人能给我一个LINK的教程或类似的东西,这将是非常有益的。

在此先感谢 Planky

+0

您可以重命名'toggleAudio'中的'playAudio'方法,并在那里处理切换播放的声音 – 2011-07-20 12:34:00

回答

1

的loadView或某处创建AVAudioPlayer选手对象。

- (void)loadView { 

    // Some code here 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Vorwort" ofType:@"mp3"]; 
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    self.audioPlayer = theAudio; 
    [theAudio release]; 
    // Some code here 
} 

然后按钮的动作中(改动作名称toggleAudio正如其他建议),就可以得到性能IsPlaying模块,看看音频是否正在播放与否,并做相应的动作。

- (void)toggleAudio { // original name is playAudio 

    if ([self.audioPlayer isPlaying]) { 

     [self.audioPlayer pause]; 
     // Or, [self.audioPlayer stop]; 

    } else { 

     [self.audioPlayer play]; 
    } 
} 
+0

您让我的一天!来自奥地利。 – Planky

+0

欢迎。来自印度的欢呼声! ;-) – EmptyStack