2011-12-28 88 views
1

我已经搜索了这个答案,但没有找到它。AVAudioPlayer - 屏蔽按钮

当我的iPhone应用程序启动时,我会在后台播放音乐。但我想要一个按钮,以便用户可以将音乐静音。在应用程序中也有声音效果,所以滑动设备侧面的静音按钮不会将其切断。

这是我用于AVAudioPlayer的当前代码。

- (void)viewDidLoad{ 
#if TARGET_IPHONE_SIMULATOR 
    //here code for use when execute in simulator 
#else 
    //in real iphone 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"FUNKYMUSIC" ofType:@"mp3"]; 
    AVAudioPlayer *TheAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    TheAudio.delegate = self; 
    [TheAudio play];  
    TheAudio.numberOfLoops = -1; 
#endif 
} 

任何人都可以帮助我一个简单的按钮所需的代码,只需停止音乐,并重新启动它。

谢谢先进。

回答

0

将这个代码在viewcontroller.h文件:

-(IBAction) btnStop:(id)sender; 

将这个代码在viewcontroller.m文件:

-(IBAction) btnStop:(id)sender { 
    [TheAudio stop]; 
    //Whatever else you want to do when the audio is stopped 
} 

在界面生成器,一个按钮连接到这个动作,所以当它被点击时,这个动作将被调用。 这应该会让音乐停止。

+0

如何将代码放入按钮?我正在使用nib文件btw。谢谢你的信息。 – user282076 2011-12-28 14:24:26

+0

使用更好的代码编辑 – DGund 2011-12-28 14:33:29

+0

感谢您对代码的更新,但'TheAudio'未声明并出错。 – user282076 2011-12-28 14:53:45

0

它更容易在回答中显示代码:

-(IBAction) playerPlay:(id)sender { 

    if([player isPlaying]) { 
     [player stop]; 
    } 
    if(![player isPlaying]) { 
     [player play]; 
    } 

} 

我会解释: 的[玩家IsPlaying模块]方法检查是否音频播放。如果正在播放音频,则会执行括号中的所有内容(在这种情况下,音频将停止播放)。

由于“!”在![player isPlaying]中,该方法与通常情况相反。这意味着如果玩家不在玩,括号中的所有内容都会被执行(在这种情况下,音频开始播放)。

所有这些都包含在IBAction中,以便在点击按钮时执行它。

以供将来参考,在Objective-C中的if语句的正确格式为:

if(thing to check for) { 
things that happen if the thing that is check for is correct; 
} 

词“那么”从未实际使用,但它是同样的事情,无论是在括号。 希望这有助于!