如何使自定义UIButton切换声音开/关

时间:2011-07-20 12:26:00

标签: iphone objective-c xcode uibutton toggle

我是n00b并寻求帮助。

现在我可以使用以下代码启动Soundfile:

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

使用相同的按钮我想停下来播放声音。 也许我正在寻找错误的东西,但我无法在网上找到适当的信息。

如果有人能给我一个关于教程或类似内容的链接,那将会非常有用。

提前谢谢 Planky

1 个答案:

答案 0 :(得分: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];
    }
}