您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 語音播放:聽筒與揚聲器的自動切換實作

編輯:iOS 程式設計技術

微信式的語音訊息有個共同特徵:手機貼近耳朵時從聽筒出聲,拿開後改由揚聲器播放。要達到這個效果,需要同時用到「接近感測器」與「AVAudioSession 音訊路由」兩套 API。本文把實作方式與容易踩的坑一起整理出來。

一、UIDevice 的兩個接近感測器屬性

UIDevice 提供了兩個相關屬性,皆需 iOS 3.0 以上:

  • proximityMonitoringEnabled:是否啟用接近監控。
  • proximityState:感測器目前是否被遮擋。

官方文件對可用性的判斷方式寫得很明確:

To determine if proximity monitoring is available, attempt to enable it. If the value of the proximityState property remains NO, proximity monitoring is not available.

也就是說:嘗試啟用之後,如果 proximityState 仍是 NO,代表這台裝置沒有接近感測器。

狀態變化會透過 UIDeviceProximityStateDidChangeNotification 通知出來。

二、基本實作

// 建議在播放前設為 YES,播放結束後設為 NO
[[UIDevice currentDevice] setProximityMonitoringEnabled:YES];

// 註冊監聽
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(sensorStateChange:)
                                             name:UIDeviceProximityStateDidChangeNotification
                                           object:nil];

#pragma mark - 處理接近監聽觸發事件
- (void)sensorStateChange:(NSNotification *)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];
    }
}

三、播放器的初始化設定

// 舊式 AudioSession C API 寫法
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];

四、比較嚴謹的監聽寫法

正式專案中建議先確認感測器是否真的可用,並在離開頁面前確實移除監聽:

// 新增監聽
[[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
if ([UIDevice currentDevice].proximityMonitoringEnabled == YES) {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(sensorStateChange:)
                                                 name:UIDeviceProximityStateDidChangeNotification
                                               object:nil];
}

// 移除監聽
if ([UIDevice currentDevice].proximityMonitoringEnabled == YES) {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIDeviceProximityStateDidChangeNotification
                                                  object:nil];
}
[[UIDevice currentDevice] setProximityMonitoringEnabled:NO];

#pragma mark - 處理接近監聽觸發事件
- (void)sensorStateChange:(NSNotification *)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;

        // 既沒有在播放,也已經離開耳邊,就可以把感測器關掉
        if (![MTool isPlayRecodering]) {
            [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
        }
    }
}

五、最容易踩的坑:切換失效

問題描述是這樣的:對於不希望常駐啟用接近感測器的 App,如果要在聽筒與揚聲器之間切換,就必須靠感測器來切換輸出模式。但如果語音在聽筒模式下播放完畢時仍然停在聽筒模式,此時若把感測器關掉,會導致後續問題:

當使用者把手機移開耳朵,因為感測器已經關閉,App 再也收不到狀態變更通知;而此時若底層音訊路由沒有被切回來,聲音就會一直卡在聽筒輸出。更麻煩的是,App 內部快取的感測器狀態仍停留在「接近」,於是整套「依感測器狀態切換音訊輸出」的邏輯就失效了。

另外還有一個機型差異需要注意:在 iPhone 4s 與 iPhone 5 上,若關閉感測器時狀態為 YES,再次啟用時不會收到變更通知;而在 iPhone 4 上,同樣情況下再次啟用則會先收到一次變更通知。這種不一致會讓跨機型的行為測試變得很棘手。

解法

核心原則只有一句:只在不熄屏的狀態下關閉接近感測器。

具體做法是——感測器啟用期間,若語音已播放結束但感測器狀態仍是 YES(尚未觸發變更),這時不要急著關閉感測器。等障礙物離開、收到狀態變更通知後,在通知裡同時檢查「感測器是否已離開」與「是否已無音訊需要播放」,兩個條件都成立時再關閉感測器即可。

六、加上手動切換

除了自動切換,實務上也常提供長按手動切換的入口。做法是先掛一個長按手勢:

UILongPressGestureRecognizer *longPress =
    [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
longPress.minimumPressDuration = 1.0;
longPress.allowableMovement = 50.0;
[self.bubbleBgImageView addGestureRecognizer:longPress];

手勢觸發時只需在狀態最初的那一刻處理一次:

- (void)longPressed:(UILongPressGestureRecognizer *)gestureRecognizer {
    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
            if ([self.voiceDelegate respondsToSelector:@selector(BaseChartVoiceLongPressed)]) {
                [self.voiceDelegate BaseChartVoiceLongPressed];
            }
            break;
        default:
            break;
    }
}

最後在委派方法裡針對目前的 category 做反向切換:

#pragma mark - BaseChartCellDelegate
- (void)BaseChartVoiceLongPressed {
    NSLog(@"voice long Pressed");
    if ([[[AVAudioSession sharedInstance] category] isEqualToString:AVAudioSessionCategoryPlayback]) {
        // 目前是揚聲器,切換為聽筒
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        [self showTipInfo:@"切換為聽筒模式"];
    } else {
        // 目前是聽筒,切換為揚聲器
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [self showTipInfo:@"切換為揚聲器模式"];
    }
}

七、現代寫法補充

上面示範混用了 C 版 AudioSession API 與 AVAudioSession,這是為了貼近原始專案的寫法。若你今天從零開始實作,建議全程使用 AVAudioSession,並用 AVAudioSessionCategoryPlayAndRecord 搭配 setPreferredInput: 或直接切換 overrideOutputAudioPort: 來控制路由,API 語意會清楚很多,也不必再手動處理.UInt32 與記憶體大小。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved