废话不多说说一下现状

网上好多关于扬声器的操作,可是问题多多。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. Android 读取asset文件

    * * 从Assets中读取图片 */ private Bitmap getImageFromAssetsFile(String fileName) { Bitmap image = null; As ...

  2. C#压缩文件夹至zip,不包含所选文件夹【转+修改】

    转自园友:jimcsharp的博文C#实现Zip压缩解压实例[转] 在此基础上,对其中的压缩文件夹方法略作修正,并增加是否对父文件夹进行压缩的方法.(因为笔者有只压缩文件夹下的所有文件,却不想将选中的 ...

  3. 网络编程基础_3.APC队列

    APC队列 #include <stdio.h> #include <windows.h> // 保存 IO 操作的结果 CHAR Buffer1[] = { }; CHAR ...

  4. CAD绘制一个图象标记对象(com接口VB语言)

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3 ...

  5. 在WEB项目中调用QQ通讯组件打开QQ聊天界面

    在很多WEB项目中,需要提供在线服务的功能,加上自己的联系方式,例如:QQ,不用添加QQ好友也可以交谈,那这到底是怎么实现的呢? 对于这个功能,需要提到一个组件,即“QQ通讯组件”.QQ通讯组件是一种 ...

  6. HDU-4705 Y(思维+dfs树)

    Input 4 1 2 1 3 1 4 Output 1 题意:给你一颗树,选择一个三个点构成的集合,使得这三个点不在一条直线上(意思就是 从一个点出发,用一条不回头的线不能将这三个点连起来)问一共有 ...

  7. freopen的各种错误姿势

    本弱鸡已经触发的错误姿势: freoprn("railway.in","r",stdin); freopen("railway.cpp",& ...

  8. python面向对象的特点,类定义等,私有属性、公有属性、成员属性

    引子:类的对象在内存中的表示def dog(name,dog_type): def bark(d): print(d,'wang wang wang ...') data = { 'name':nam ...

  9. Python学习笔记之map、zip和filter函数

    这篇文章主要介绍 Python 中几个常用的内置函数,用好这几个函数可以让自己的代码更加 Pythonnic 哦 1.map map() 将函数 func 作用于序列 seq 的每一个元素,并返回处理 ...

  10. PAT 1143 Lowest Common Ancestor

    The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...