石ころです。SNSを作っています。
主にBluetooth再生周りで困っています。
下記、ご助言頂けますと大変幸いです。
実現したいこと
(1) Bluetoothイヤホン未装着時
・セルをタップ:スピーカー再生
・近接センサー作動時:iPhone上部のスピーカーから小音量で自動再生(通話の時に使うスピーカーです)
※近接センサーはiPhone上部のセンサーを指し、上を覆い隠すと検知されます。iPhoneを耳元に持ってきたときに検知されるようにしています。
(2) Bluetoothイヤホン装着時
・セルをタップ:Bluetoothイヤホンから再生
・近接センサー作動時:Bluetoothイヤホンから再生
まず、(1)を実現するために、次のコードを書きました。
コード
Swift
1 2 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 3 let audioSession = AVAudioSession.sharedInstance() 4 do { 5 try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker) 6 } catch let error as NSError { 7 } 8 } 9
Swift
1 @objc func proximitySensorStateChanged(){ 2 if (UIDevice.current.proximityState == true) { 3 do{ 4 let audioSession = AVAudioSession.sharedInstance() 5 do { 6 try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.none) 7 } catch let error as NSError { 8 print("audioSession error: (error.localizedDescription)") 9 } 10 //中略:音声再生処理を記載しています 11} catch {} 12} 13}
上記コードにより、冒頭の(1)は問題なく実現できます。
次に、Bluetooth再生を可能にするために、下記のコードを追記しました。
Swift
1 2 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 3 (追記始まり)--------------------------------- 4 do{ 5 try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, options: AVAudioSession.CategoryOptions.mixWithOthers) 6 //mixWithOthersをallowBluetoothやduckOthersに変えてみても結果は同じ 7 } catch { 8 } 9 (追記終わり)--------------------------------------- 10 let audioSession = AVAudioSession.sharedInstance() 11 do { 12 try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker) 13 } catch let error as NSError { 14 } 15 } 16
上記により、Bluetooth再生は問題なく出来るようになる代わりに、この状態でiPhoneのBluetoothをOFFにし、一度セルタップ再生をした後に近接センサーを覆い隠し再生させると、上部スピーカーでの小音再生ではなく、通常スピーカーの大音量再生になってしまいます。
一度でもAVAudioSession.CategoryOptions.mixWithOthersが実行されてしまうと、近接センサー再生では通常スピーカー再生になってしまうようです。
お気付きの点ございましたら、お手数ですが、アドバイス頂けますと幸いです。
よろしくお願い致します。
あなたの回答
tips
プレビュー