如何打开/关闭声音

时间:2014-02-25 05:35:37

标签: ios objective-c avaudioplayer

我在DetailViewController中创建了一个声音,

 soundFileURL = [[NSBundle mainBundle] URLForResource:@"click" withExtension:@"wav"];
s1Player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
s1Player.delegate = self;
s1Player.volume = 2;
[s1Player play];

我想在我的ViewController中控制上面的声音。我在ViewController中创建了一个按钮,并切换它(声音打开/关闭)。

我试过了, DetailViewController.m

ViewController *viewController = [[ViewController alloc] init];
if(viewController.stopSound) {
    [s1Player stop];
    s1Player.volume = 0;
}
else {
   [s1Player play];
    s1Player.volume = 2;
}

ViewController.h

@property BOOL stopSound;
ViewController.m中的

- (void) setSoundAction {

if(_stopSound){
    _stopSound = NO;
}
else{
    _stopSound = YES;
}
}

如果上述代码不易理解或未清除,请建议我如何在DetailViewController上切换按钮,声音开启和声音关闭。因为Sound放在DetailViewController上。

1 个答案:

答案 0 :(得分:0)

你想要的只是切换按钮,那么这个怎么样?

-(void)viewDidLoad
{
    [super viewDidLoad];

    UIButton *toggleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    toggleButton.frame = CGRectMake(10.0, 10.0, 40.0, 40.0);
    [toggleButton setTitle:@"Toggle" forState:UIControlStateNormal];
    [toggleButton addTarget:self action:@selector(toggleSound:) forControlEvents:UIControlEventTouchUpInside];  //execute the method when touched
    [self.view addSubview:toggleButton];
}

- (void)toggleSound:(UIButton *)btn
{
    static BOOL muted;  //remember the current status of AVAudioPlayer object.
    muted = !muted;     //toggle!!

    if(muted) {
        s1player.volume = 0.0;
    } else {
        s2player.volume = 1.0;  //max value for volume is 1.0
    }
}