下面是一個完整的微信小程序實現方案,當藍牙設備連接時自動播放背景音樂(BGM)。
實現思路
監聽藍牙設備連接狀態
當檢測到藍牙設備連接時,自動播放音樂
當藍牙斷開時,停止音樂播放
處理相關權限和用戶交互
完整代碼實現
1. 項目結構
text
/pages/indexindex.jsindex.jsonindex.wxmlindex.wxss
2. index.wxml
xml
<view class="container"><view class="status">當前藍牙狀態: {{bluetoothStatus}}</view><button bindtap="initBluetooth">初始化藍牙</button><button bindtap="startSearch">搜索設備</button><view class="devices"><block wx:for="{{devices}}" wx:key="deviceId"><view class="device" bindtap="connectDevice" data-device="{{item}}">{{item.name}} ({{item.deviceId}})</view></block></view><audio id="bgm" src="/assets/bgm.mp3" loop></audio> </view>
3. index.wxss
css
.container {padding: 20px; }.status {margin: 20px 0;font-size: 16px;color: #333; }button {margin-bottom: 10px; }.device {padding: 10px;border: 1px solid #eee;margin-bottom: 5px; }
4. index.js
javascript
Page({data: {bluetoothStatus: '未初始化',devices: [],connectedDeviceId: null,audioCtx: null},onLoad() {// 創建音頻上下文this.setData({audioCtx: wx.createInnerAudioContext()});this.data.audioCtx.src = '/assets/bgm.mp3';this.data.audioCtx.loop = true;// 監聽藍牙適配器狀態this.onBluetoothAdapterStateChange();},// 初始化藍牙initBluetooth() {wx.openBluetoothAdapter({success: (res) => {console.log('藍牙初始化成功', res);this.setData({ bluetoothStatus: '已初始化,未連接' });this.startBluetoothDevicesDiscovery();},fail: (err) => {console.error('藍牙初始化失敗', err);wx.showToast({title: '請打開手機藍牙',icon: 'none'});}});},// 開始搜索設備startSearch() {this.startBluetoothDevicesDiscovery();},// 開始發現設備startBluetoothDevicesDiscovery() {wx.startBluetoothDevicesDiscovery({success: (res) => {console.log('開始搜索設備', res);this.onBluetoothDeviceFound();},fail: (err) => {console.error('搜索設備失敗', err);}});},// 監聽發現新設備事件onBluetoothDeviceFound() {wx.onBluetoothDeviceFound((res) => {const devices = res.devices;console.log('發現新設備', devices);if (devices.length > 0) {this.setData({devices: this.data.devices.concat(devices)});}});},// 連接設備connectDevice(e) {const device = e.currentTarget.dataset.device;const deviceId = device.deviceId;wx.createBLEConnection({deviceId,success: (res) => {console.log('連接成功', res);this.setData({ bluetoothStatus: `已連接: ${device.name}`,connectedDeviceId: deviceId});// 連接成功后播放BGMthis.playBGM();},fail: (err) => {console.error('連接失敗', err);}});},// 播放背景音樂playBGM() {this.data.audioCtx.play();wx.showToast({title: '藍牙已連接,開始播放音樂',icon: 'none'});},// 停止背景音樂stopBGM() {this.data.audioCtx.stop();wx.showToast({title: '藍牙已斷開,停止播放音樂',icon: 'none'});},// 監聽藍牙適配器狀態變化onBluetoothAdapterStateChange() {wx.onBluetoothAdapterStateChange((res) => {console.log('藍牙適配器狀態變化', res);if (!res.available) {this.setData({ bluetoothStatus: '藍牙不可用' });this.stopBGM();} else if (res.discovering) {this.setData({ bluetoothStatus: '正在搜索設備...' });} else {this.setData({ bluetoothStatus: '藍牙已開啟' });}});},// 監聽BLE連接狀態變化onBLEConnectionStateChange() {wx.onBLEConnectionStateChange((res) => {console.log('BLE連接狀態變化', res);if (res.connected) {this.setData({ bluetoothStatus: `已連接: ${res.deviceId}`,connectedDeviceId: res.deviceId});this.playBGM();} else {this.setData({ bluetoothStatus: '藍牙已斷開',connectedDeviceId: null});this.stopBGM();}});},onUnload() {// 頁面卸載時停止搜索和斷開連接wx.stopBluetoothDevicesDiscovery();if (this.data.connectedDeviceId) {wx.closeBLEConnection({ deviceId: this.data.connectedDeviceId });}wx.closeBluetoothAdapter();// 停止音樂this.data.audioCtx.stop();this.data.audioCtx.destroy();} });
5. index.json
json
{"usingComponents": {},"requiredBackgroundModes": ["audio", "bluetooth"] }
關鍵點說明
權限配置:
在
app.json
中配置requiredBackgroundModes
以保證后臺運行權限需要用戶授權藍牙和音頻權限
藍牙流程:
初始化藍牙適配器(
openBluetoothAdapter
)開始搜索設備(
startBluetoothDevicesDiscovery
)監聽發現設備(
onBluetoothDeviceFound
)連接設備(
createBLEConnection
)監聽連接狀態(
onBLEConnectionStateChange
)
音頻控制:
使用
wx.createInnerAudioContext
創建音頻上下文連接成功時調用
play()
方法斷開連接時調用
stop()
方法
用戶體驗:
顯示藍牙狀態變化
連接/斷開時有Toast提示
頁面卸載時清理資源
注意事項
真機測試:
此功能必須在真機上測試,開發者工具可能無法完全模擬藍牙功能
音頻文件:
將背景音樂文件放在
/assets/
目錄下確保音頻文件格式兼容(建議使用mp3格式)
藍牙限制:
iOS和Android的藍牙API有差異,需測試兼容性
部分舊機型可能不支持某些藍牙功能
后臺播放:
小程序進入后臺后可能會被暫停,需要合理配置后臺運行權限
用戶授權:
首次使用藍牙功能時需要用戶授權
處理用戶拒絕授權的場景
這個實現提供了完整的藍牙連接監聽和音頻自動播放功能,你可以根據實際需求進一步定制UI和交互邏輯。