废话不多说说一下现状

网上好多关于扬声器的操作,可是问题多多。SDK7.X 和SDK7.X以上版本号有点诧异

#import <Foundation/Foundation.h>

#import <AudioToolbox/AudioToolbox.h>

#import <AVFoundation/AVFoundation.h>

@interface AudioManager :
NSObject

{

AVAudioPlayer *m_audioPlayer;

}

@property (atomic,
readonly)BOOL _isSpeakerOn;

@property (atomic,
readonly)BOOL _isHeadsetOn;

+(AudioManager*)shared;

// 打开扬声器

- (void)setSpeakerOn;

// 关闭扬声器

- (void)setSpeakerOff;

@end

//

//  AudioManager.m

//  AvconNetAndCallDemo

//

//  Created by zjq on 14-7-21.

//  Copyright (c) 2014年 zjq. All rights reserved.

//

#import "AudioManager.h"

#import <UIKit/UIKit.h>

#define IOSVersion [[UIDevice currentDevice].systemVersion floatValue]

@implementation AudioManager

@synthesize _isSpeakerOn;

@synthesize _isHeadsetOn;

- (id)init

{

self = [super
init];

if (self) {

_isSpeakerOn = NO;

AVAudioSession *audioSession = [AVAudioSession
sharedInstance];

//默认情况下扬声器播放

[audioSession setCategory:AVAudioSessionCategoryPlayback
withOptions:AVAudioSessionCategoryOptionMixWithOthers 
error:nil];

[audioSession
setActive:YES
error:nil];

UInt32 sessionCategory =
kAudioSessionCategory_MediaPlayback;

AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,

sizeof(sessionCategory),

&sessionCategory);

UInt32 audioRouteOverride =
kAudioSessionOverrideAudioRoute_Speaker;

AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,

sizeof (audioRouteOverride),

&audioRouteOverride);

AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange,

audioRouteChangeListenerCallback, (__bridge
void *)(self));

}

return
self;

}

static
AudioManager *_audioManager =
NULL;

+(AudioManager*)shared

{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

_audioManager = [[AudioManager
alloc]
init];

});

return
_audioManager;

}

- (void)setSpeakerOn

{

NSLog(@"setSpeakerOn:%d",[NSThread
isMainThread]);

UInt32 doChangeDefaultRoute =
kAudioSessionOverrideAudioRoute_Speaker;

AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,

sizeof (doChangeDefaultRoute),

&doChangeDefaultRoute

);

_isSpeakerOn = [self
checkSpeakerOn];

_isHeadsetOn = NO;

//[self resetOutputTarget];

}

- (void)setSpeakerOff

{

UInt32 doChangeDefaultRoute =
kAudioSessionOverrideAudioRoute_None;

AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,

sizeof (doChangeDefaultRoute),

&doChangeDefaultRoute

);

_isSpeakerOn = [self
checkSpeakerOn];

}

- (BOOL)checkSpeakerOn

{

CFStringRef route;

UInt32 propertySize =
sizeof(CFStringRef);

AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &route);

if((route == NULL) || (CFStringGetLength(route) ==
))

{

// Silent Mode

NSLog(@"AudioRoute: SILENT, do nothing!");

}

else

{

NSString* routeStr = (__bridge
NSString*)route;

NSRange speakerRange = [routeStr
rangeOfString : @"Speaker"];

if (speakerRange.location !=
NSNotFound)

return YES;

}

return
NO;

}

- (BOOL)hasHeadset

{

CFStringRef route;

UInt32 propertySize =
sizeof(CFStringRef);

AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &route);

if((route == NULL) || (CFStringGetLength(route) ==
))

{

// Silent Mode

NSLog(@"AudioRoute: SILENT, do nothing!");

}

else

{

NSString* routeStr = (__bridge
NSString*)route;

NSLog(@"AudioRoute: %@", routeStr);

if ([routeStr isEqualToString:@"ReceiverAndMicrophone"]) {

//            static dispatch_once_t onceToken;

//            dispatch_once(&onceToken, ^{

//                [self setSpeakerOn];

//            });

[self
setSpeakerOn];

}

NSRange headphoneRange = [routeStr
rangeOfString : @"Headphone"];

NSRange headsetRange = [routeStr
rangeOfString : @"Headset"];

if (headphoneRange.location !=
NSNotFound)

{

return YES;

}
else if(headsetRange.location !=
NSNotFound)

{

return YES;

}

}

return
NO;

}

// 推断麦克风是否实用

- (BOOL)hasMicphone

{

return [[AVAudioSession
sharedInstance] isInputAvailable];

}

- (void)erjiOutPutTarget

{

BOOL hasHeadset = [self
hasHeadset];

if (hasHeadset) {

_isHeadsetOn = YES;

}

NSLog (@"Will Set output target is_headset = %@ .", hasHeadset?@"YES":@"NO");

UInt32 audioRouteOverride =
kAudioSessionOverrideAudioRoute_None;

AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute,
sizeof(audioRouteOverride), &audioRouteOverride);

}

- (void)resetOutputTarget

{

BOOL hasHeadset = [self
hasHeadset];

NSLog (@"Will Set output target is_headset = %@ .", hasHeadset?@"YES":@"NO");

UInt32 audioRouteOverride = 
kAudioSessionOverrideAudioRoute_Speaker;

AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute,
sizeof(audioRouteOverride), &audioRouteOverride);

_isHeadsetOn =
NO;

}

void audioRouteChangeListenerCallback (void *inUserData,
AudioSessionPropertyID inPropertyID,
UInt32 inPropertyValueS, const
void *inPropertyValue)

{

if (inPropertyID !=
kAudioSessionProperty_AudioRouteChange)

return;

// Determines the reason for the route change, to ensure that it is not

// because of a category change.

CFDictionaryRef routeChangeDictionary = (CFDictionaryRef)inPropertyValue;

CFNumberRef routeChangeReasonRef = (CFNumberRef)CFDictionaryGetValue (routeChangeDictionary,
CFSTR (kAudioSession_AudioRouteChangeKey_Reason));

SInt32 routeChangeReason;

CFNumberGetValue (routeChangeReasonRef,
kCFNumberSInt32Type, &routeChangeReason);

NSLog(@"<<<RouteChangeReason: %d",(int)routeChangeReason);

NSLog(@"[=======%@",inUserData);

AudioManager *pMgr = (__bridge
AudioManager *)inUserData;

//没有耳机

if (routeChangeReason ==
kAudioSessionRouteChangeReason_OldDeviceUnavailable)

{

[pMgr
setSpeakerOn];

[pMgr resetOutputTarget];

}

else
if (routeChangeReason ==
kAudioSessionRouteChangeReason_NewDeviceAvailable)

{

[pMgr
erjiOutPutTarget];

}else
if (routeChangeReason ==
kAudioSessionRouteChangeReason_Override){

[pMgr
setSpeakerOn];

[pMgr resetOutputTarget];

}

NSLog(@"-------->%f",IOSVersion);

//if (IOSVersion >= 8.0) {

) {

[pMgr
hasHeadset];

}

//}

}

//- (BOOL)isAirplayActived

//{

//    CFDictionaryRef currentRouteDescriptionDictionary = nil;

//    UInt32 dataSize = sizeof(currentRouteDescriptionDictionary);

//    AudioSessionGetProperty(kAudioSessionProperty_AudioRouteDescription, &dataSize, &currentRouteDescriptionDictionary);

//

//    BOOL airplayActived = NO;

//    if (currentRouteDescriptionDictionary)

//    {

//        CFArrayRef outputs = CFDictionaryGetValue(currentRouteDescriptionDictionary, kAudioSession_AudioRouteKey_Outputs);

//        if(outputs != NULL && CFArrayGetCount(outputs) > 0)

//        {

//            CFDictionaryRef currentOutput = CFArrayGetValueAtIndex(outputs, 0);

//            //Get the output type (will show airplay / hdmi etc

//            CFStringRef outputType = CFDictionaryGetValue(currentOutput, kAudioSession_AudioRouteKey_Type);

//

//            airplayActived = (CFStringCompare(outputType, kAudioSessionOutputRoute_AirPlay, 0) == kCFCompareEqualTo);

//        }

//        CFRelease(currentRouteDescriptionDictionary);

//    }

//    return airplayActived;

//}

/*

- (void)openloudspeaker{

//初始化播放器的时候例如以下设置

UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;

AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,

sizeof(sessionCategory),

&sessionCategory);

UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;

AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,

sizeof (audioRouteOverride),

&audioRouteOverride);

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

//默认情况下扬声器播放

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

[audioSession setActive:YES error:nil];

[self handleNotification:YES];

}

#pragma mark - 监听听筒or扬声器

- (void) handleNotification:(BOOL)state

{

[[UIDevice currentDevice] setProximityMonitoringEnabled:state]; //建议在播放之前设置yes。播放结束设置NO,这个功能是开启红外感应

if(state)//加入监听

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(sensorStateChange:) name:@"UIDeviceProximityStateDidChangeNotification"

object:nil];

else//移除监听

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIDeviceProximityStateDidChangeNotification" object:nil];

}

//处理监听触发事件

-(void)sensorStateChange:(NSNotificationCenter *)notification;

{

//假设此时手机靠近面部放在耳朵旁,那么声音将通过听筒输出,并将屏幕变暗(省电啊)

if ([[UIDevice currentDevice] proximityState] == YES)

{

NSLog(@"Device is close to user");

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

}

else

{

NSLog(@"Device is not close to user");

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

}

}

*/

@end


iOS 打开扬声器以及插入耳机的操作的更多相关文章

  1. 电脑没有声音,显示“未插入耳机或扬声器”,检测不到Realtek高清晰音频管理器

    2018-7-16,电脑彻夜未关,早上发现已经死机了.关机重启之后,就发现没有声音了,提示“未插入耳机或扬声器”,并且检测不到Realtek高清晰音频管理器,只能检查到显卡音频输出.首先,音箱在其他电 ...

  2. 腾讯优测优分享 | 你是否体验过Android手机插入耳机后仍外放的尴尬?

    腾讯优测是专业的移动自动化测试平台,提供多维度的自动化测试服务,让测试更简单! 近期有报道称,澳大利亚悉尼市新某大学的一名男生在课堂上看电影,不料耳机没有插好,变成了现场直播... 如果你认为耳机没插 ...

  3. 【win10】大水牛主机插入耳机没有声音

    主机:大水牛,技嘉主板 操作系统:win10 问题:主机前面插入耳机,没有声音,扬声器图标出错 解决 一..插入耳机 二..Realtek高清晰音频管理器 1.打开音频管理器,点击右下角的设置 2.点 ...

  4. win10大水牛主机插入耳机没有声音

    主机:大水牛,技嘉主板 操作系统:win10 问题:主机前面插入耳机,没有声音,扬声器图标出错 解决 一..插入耳机 二..Realtek高清晰音频管理器 1.打开音频管理器,点击右下角的设置 2.点 ...

  5. 为什么我的mac插入耳机耳机没有声音呢?

    macOS 系统莫名其妙就遇到声音和音频播放问题的情况相当普遍,在新添音频设备.应用程序之间进行切换或更新操作系统后,都可能会遇到音频错误.好加在,解决大多数 macOS 声音无法正常工作的方法都非常 ...

  6. iOS 打开本地 其他应用程序(URL Types)

    iOS 打开本地其他应用程序(URL Types) /*前言废话:Xcode是神奇的,是我所见到的编译器中最为神奇的,如:它可以同时运行两个甚至更多Project到我们模拟器上,可以同时使用一个模拟器 ...

  7. IOS学习之IOS沙盒(sandbox)机制和文件操作

    IOS学习之IOS沙盒(sandbox)机制和文件操作(一) 1.IOS沙盒机制 IOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都 ...

  8. ios 推送app badge 数字累加操作

    ios 推送app badge 数字累加操作: 一:此数字需要后台配合: 二:大致原理: 后台发推送时,第一次 传badge 为1,往后,依次累加操作即可: 当用户打开app时,app向后台发送请求, ...

  9. 解决window10系统电脑插入耳机之后没有声音的问题

    其实办法也是从百度百科上查到的 ⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄     可能是因为自己某个不小心的操作更改了设置 1. 首先要点开设置按钮,在搜索栏输入控制面板 (当然知道控制面板在哪里的小伙伴就不用 ...

随机推荐

  1. Dota2团战实力蔑视人类,解剖5只“AI英雄”

    去年,OpenAI 在 DOTA 的 1v1 比赛中战胜了职业玩家 Dendi,而在距离进阶版 OpenAI Five 系统战胜人类业余玩家不过一个月的时间,今天凌晨,它又以 2:1 的战绩再次完成对 ...

  2. apache hadoop 伪分布式安装

    1. 准备工作 1.1. 软件准备 1.安装VMWare 2.在VMWare上安装CentOS6.5 3.安装XShell5,用来远程登录系统 4.通过rpm -qa | grep ssh 检查cen ...

  3. 好用的sublime插件以及快捷键

    管理插件:使用Ctrl+`(Esc键下方)快捷键或者通过View->Show Console菜单打开命令行 import urllib.request,os,hashlib; h = '2915 ...

  4. Digital design之Boolean Algebra

    1. 0 and 1 (duality: 0 -- 1, · -- +) X + 0 = X, X · 1 = X X + 1 = 1, X · 0 = 0 2. Idempotent X + X = ...

  5. union与union all

    union在合并A和B表的时候会先将B表中的数据与A表进行比较,若A表中已存在,则忽略. union all合并时则不比较,直接将A表与B表进行合并. 因此,若已知A与B不存在重复数据,那么union ...

  6. 模拟title提示!

    转载http://wouit.com/post/2013-08-15/40052169981html <a href="#" tishi="常见的网页新闻循环跳动显 ...

  7. Apache添加到windows服务和移除Apache的windows服务

    Apache添加到windows服务和移除Apache的windows服务 Apache免安装版将其添加到Windows服务中: 打开cmd控制台,在上面输入"你的Apache安装目录\bi ...

  8. 打造个人的vimIDE

    环境说明 系统版本:centos7.Ubuntu16 vim版本:7.4 安装git工具 整体说明:本文的vim配置是针对Linux的单个系统用户,python的自动补全使用的是 jedi-vim 插 ...

  9. P1269 信号放大器

    P1269 信号放大器 给一棵有根树,树的边上有距离.根上有一个信号发射器,会发生强度为 h 的信号,信号会往所有的节点传播,然而每经过一条边强度就会削减距离的大小,当信号到达某点时小于 1,则信号传 ...

  10. ZOJ - 3981 - Balloon Robot (思维)

    参考自:https://blog.csdn.net/qq_36553623/article/details/78445558 题意: 第一行三个数字n, m, q表示有m个座位围成一个环,n个队伍,q ...