首页 > 解决方案 > 使用 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。任何帮助,将不胜感激。谢谢!

标签: swiftxcodebluetoothcore-bluetooth

解决方案


推荐阅读