swift - 使用 swift 和 Xcode 连接扬声器
问题描述
import UIKit
import CoreBluetooth
import AVFoundation
class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager: CBCentralManager!
var myPeripheral: CBPeripheral!
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Initialize central manager
centralManager = CBCentralManager(delegate: self, queue: nil)
// Audio
do {
audioPlayer = try AVAudioPlayer(contentsOf:
URL.init(fileURLWithPath: Bundle.main.path(forResource: "bell", ofType: "wav")!))
audioPlayer.prepareToPlay()
} catch{
print(error)
}
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
// Turned on
if central.state == CBManagerState.poweredOn {
print("BLE powered on.")
central.scanForPeripherals(withServices: nil, options: nil)
}
// Not on, could be different issues
else {
print("Something wrong with BLE.")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber){
// Get the peripheral.name
if let pname = peripheral.name{
print(pname)
if pname == "Speaker_Name"{
// found wanted device so stop
self.centralManager.stopScan()
// assign it to myperipheral object
self.myPeripheral = peripheral
self.myPeripheral.delegate = self
//
self.centralManager.connect(peripheral, options: nil)
}
}
}
// Connected
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
self.myPeripheral.discoverServices(nil)
print("Connected")
}
@IBAction func clickBell(_ sender: Any) {
audioPlayer.play()
}
}
如何使用 swift 连接到扬声器而无需在蓝牙设置中连接到扬声器。一旦我让这部分代码工作,我的意图是允许应用程序连接并在多个扬声器上播放铃声。这是我目前拥有的代码,它没有连接到我想要的扬声器,但它能够连接到其他设备,例如电视和我的 AirPods。任何帮助,将不胜感激。谢谢!
解决方案
推荐阅读
- python - Unable to remove accented special characters in a string despite using regex
- excel - Subtract two cells based on multiple criteria
- c# - Dynamicly created panels location distance
- c - 在 C 中使用循环的非重复随机数
- ms-access - MS_Access 报表设计视图非常慢
- swift - How to not cause dark gray color to be transparent removing background from image
- microsoft-graph-calendar - 令人困惑的 Microsoft GraphAPI 限制行为
- aws-lambda - lambda 函数中的跨栈引用
- haproxy - HAProxy 1.8 使用 tcp-request inspect-delay 延迟 http/2 (h2) 请求
- javascript - create dialog that cannot be dismissed with ESC