【问题标题】:Mute AVAudioPlayer Background music with UISwitch使用 UISwitch 静音 AVAudioPlayer 背景音乐
【发布时间】:2015-11-19 12:16:22
【问题描述】:

我对编程很陌生,我正在开发我的第一个应用程序。几个星期以来,我一直无法找到答案。我真的很感激一些帮助。

我通过 AVAudioPlayer(我的应用程序中唯一的声音)播放背景音乐,当我的应用程序打开时开始播放 - 这是我的 appdelegate.m 中的代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSString *bgmusic=[[NSBundle mainBundle]pathForResource:@"cloud_two-full-" ofType:@"mp3"];
    bgmusic1=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:bgmusic] error:NULL];
    bgmusic1.delegate=self;
    bgmusic1.numberOfLoops=-1;

    [bgmusic1 play];
    [bgmusic1 setVolume:1.0];
}

所以,我创建了一个 uiswitch,我想用它来静音背景音乐。这是我的 viewcontroller.m 中的 IBAction:

- (IBAction)speakerOnOff:(id)sender {
    static BOOL muted = NO;

    if (muted) {
        [bgmusic1 setVolume:1.0];
    } else {
        [bgmusic1 setVolume:0.0];
    }
    muted = !muted;
}

但是当我点击开关关闭时,音乐继续以正常音量播放。我只有 1 个视图控制器。请帮忙!我只是希望当开关被点击关闭时音乐静音,然后当开关重新打开时回到音量 1.0。

【问题讨论】:

    标签: ios avaudioplayer uiswitch mute


    【解决方案1】:

    写下这段代码

    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
    

    上面

    bgmusic1=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:bgmusic] error:NULL];
    

    让你的按钮动作像这样

    - (IBAction)speakerOnOff:(id)sender {
        if ( bgmusic1.volume == 0) {
            bgmusic1.volume = 1;
        } else {
            bgmusic1.volume =0;
        }
    }
    

    【讨论】:

    • 感谢您的快速回复。我把那个代码放进去并运行模拟器。背景音乐仍然没有静音...还有什么我做错了吗?
    • 另外,当我为“Event”创建“- (IBAction)speakerOnOff:(id)sender”时,我选择了“Value Changed”是正确的选择吗?
    • 让按钮的发送事件 Touch Up Inside
    • 添加断点检查代码是否正在执行。
    • 我使用的是 UISwitch 而不是按钮,这会有什么不同吗?
    猜你喜欢
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多