1

我已经搜索过这个答案,但没有找到。

当我的 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
}

任何人都可以帮我编写一个简单按钮所需的代码,以简单地停止音乐并重新开始。

提前致谢。

4

2 回答 2

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
}

在界面构建器中,将一个按钮连接到此操作,因此当单击它时,将调用此操作。那应该让音乐停止。

于 2011-12-28T14:00:58.040 回答
0

在答案中显示代码更容易:

-(IBAction) playerPlay:(id)sender {

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

}

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

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

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

为了将来参考,Objective-C 中 If 语句的正确格式是:

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

“then”这个词实际上从未被使用过,但它是同一个东西,无论括号中的内容是什么。希望这可以帮助!

于 2011-12-28T16:43:48.373 回答