如何以编程方式感知iPhone静音开关?

时间:2008-11-13 17:09:12

标签: ios audio avaudiosession

我似乎无法在SDK中找到如何以编程方式感知iPhone上的静音按钮/开关。当我的应用程序播放背景音乐时,它会正确响应音量按钮,而我没有任何代码可以遵循,但是,当我使用静音开关时,它只会继续播放。

如何测试静音位置?

(注意:我的程序有自己的静音开关,但我希望物理开关覆盖它。)

10 个答案:

答案 0 :(得分:29)

谢谢,JPM。实际上,你提供的链接会得到正确的答案(最终。;)为了完整性(因为S.O.应该是QUICK答案的来源!)......

// "Ambient" makes it respect the mute switch
// Must call this once to init session
if (!gAudioSessionInited)
{
    AudioSessionInterruptionListener    inInterruptionListener = NULL;
    OSStatus    error;
    if ((error = AudioSessionInitialize (NULL, NULL, inInterruptionListener, NULL)))
    {
        NSLog(@"*** Error *** error in AudioSessionInitialize: %d.", error);
    }
    else
    {
        gAudioSessionInited = YES;
    }
}

SInt32  ambient = kAudioSessionCategory_AmbientSound;
if (AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (ambient), &ambient))
{
    NSLog(@"*** Error *** could not set Session property to ambient.");
}

答案 1 :(得分:11)

我回答了类似的问题here (link)。相关代码:

 -(BOOL)silenced {
     #if TARGET_IPHONE_SIMULATOR
         // return NO in simulator. Code causes crashes for some reason.
         return NO;
     #endif

    CFStringRef state;
    UInt32 propertySize = sizeof(CFStringRef);
    AudioSessionInitialize(NULL, NULL, NULL, NULL);
    AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
    if(CFStringGetLength(state) > 0)
            return NO;
    else
            return YES;

    }

答案 2 :(得分:7)

如果您不在静音模式下,其他答案中的某些代码(包括已接受的答案)可能无效。

我编写了下面的例程,切换到环境,读取开关,然后返回到我的应用程序中需要的设置。

-(BOOL)muteSwitchEnabled {

#if TARGET_IPHONE_SIMULATOR
    // set to NO in simulator. Code causes crashes for some reason.
    return NO;
#endif

// go back to Ambient to detect the switch
AVAudioSession* sharedSession = [AVAudioSession sharedInstance];
[sharedSession setCategory:AVAudioSessionCategoryAmbient error:nil];

CFStringRef state;
UInt32 propertySize = sizeof(CFStringRef);
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);

BOOL muteSwitch = (CFStringGetLength(state) <= 0);
NSLog(@"Mute switch: %d",muteSwitch);

// code below here is just restoring my own audio state, YMMV
_hasMicrophone = [sharedSession inputIsAvailable];
NSError* setCategoryError = nil;

if (_hasMicrophone) {

    [sharedSession setCategory: AVAudioSessionCategoryPlayAndRecord error: &setCategoryError];

    // By default PlayAndRecord plays out over the internal speaker.  We want the external speakers, thanks.
    UInt32 ASRoute = kAudioSessionOverrideAudioRoute_Speaker;
    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                             sizeof (ASRoute),
                             &ASRoute
                             );
}
else
    // Devices with no mike don't support PlayAndRecord - we don't get playback, so use just playback as we don't have a microphone anyway
    [sharedSession setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];

if (setCategoryError)
    NSLog(@"Error setting audio category! %@", setCategoryError);

return muteSwitch;
}

答案 3 :(得分:5)

为了找出静音开关音量控制的状态,我写了这两个功能。如果您希望在尝试创建音频输出之前警告用户,这些是理想的选择。

-(NSString*)audioRoute
{
    CFStringRef state;
    UInt32 propertySize = sizeof(CFStringRef);
    OSStatus n = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
    if( n )
    {
        // TODO: Throw an exception
        NSLog( @"AudioSessionGetProperty: %@", osString( n ) );
    }

    NSString *result = (NSString*)state;
    [result autorelease];
    return result;
}

-(Float32)audioVolume
{
    Float32 state;
    UInt32 propertySize = sizeof(CFStringRef);
    OSStatus n = AudioSessionGetProperty(kAudioSessionProperty_CurrentHardwareOutputVolume, &propertySize, &state);
    if( n )
    {
        // TODO: Throw an exception
        NSLog( @"AudioSessionGetProperty: %@", osString( n ) );
    }
    return state;
}

答案 4 :(得分:5)

-(BOOL)isDeviceMuted
{
 CFStringRef state;
 UInt32 propertySize = sizeof(CFStringRef);
 AudioSessionInitialize(NULL, NULL, NULL, NULL);
 AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);
 return (CFStringGetLength(state) > 0 ? NO : YES);
}

答案 5 :(得分:4)

OLIE,

我相信你可以在这里找到问题的答案:

https://devforums.apple.com/message/1135#1135

我假设您可以访问Apple.com上的开发者论坛:)

答案 6 :(得分:4)

我在这里遵循了一般理论,并将其付诸实践 http://inforceapps.wordpress.com/2009/07/08/detect-mute-switch-state-on-iphone/

这是一个回顾:播放一段短暂的无声音。时间玩多长时间。如果静音开关打开,则声音的播放将比声音本身短得多。我使用了500毫秒的声音,如果播放的声音少于这个时间,则静音开关打开。我使用音频服务播放静音(总是尊重静音开关)。本文说您可以使用AVAudioPlayer播放此声音。如果您使用AVAudioPlayer,我假设您需要设置AVAudioSession的类别以遵守静音开关,但我还没试过它。

答案 7 :(得分:3)

使用环境模式播放视频,使用 PlayAndRecord 模式在相机屏幕上录制视频,解决了我们的问题。

应用程序中的代码:didFinishLaunchingWithOptions:

NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
[[AVAudioSession sharedInstance] setMode:AVAudioSessionModeVideoRecording error:&error];
[[AVAudioSession sharedInstance] setActive:YES error:&error];

cameraController上viewWillAppear中的代码,如果您必须在应用中使用相机或录制

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

cameraController上的viewWillDisappear中的代码

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

使用这些行,我们的应用程序记录并播放视频和静音开关在iOS8和iOS7下都能完美运行!!!

答案 8 :(得分:2)

  

对于Swift

下面的框架在设备中完美运行

https://github.com/akramhussein/Mute

只需使用 pod 安装或从Git下载

即可
pod 'Mute'

并使用如下代码

import UIKit
import Mute

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel! {
        didSet {
            self.label.text = ""
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Notify every 2 seconds
        Mute.shared.checkInterval = 2.0

        // Always notify on interval
        Mute.shared.alwaysNotify = true

        // Update label when notification received
        Mute.shared.notify = { m in
            self.label.text = m ? "Muted" : "Not Muted"
        }

        // Stop after 5 seconds
        DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
            Mute.shared.isPaused = true
        }

        // Re-start after 10 seconds
        DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
            Mute.shared.isPaused = false
        }
    }

}

答案 9 :(得分:1)

这里有两个如何使用AudioSessionInitialize的例子: http://www.restoroot.com/Blog/2008/12/25/audiosessioninitialize-workarounds/