如何在检测到我的蓝牙设备时播放声音

How to play a sound when my bluetooth device is detected

今天早上开始 python 编程,想制作一个简单的应用程序,当我在附近播放歌曲时,它会嗅探我的 phone 的蓝牙。这个应用程序继续每 27 秒搜索一次我的蓝牙。如果我还在,它会继续播放,但我离开或关闭蓝牙,我希望它停止播放歌曲。我有以下代码,一切正常,但如果没有检测到蓝牙设备并且当我离开或关闭我的设备时,我会收到一个停止执行的错误,歌曲会继续播放。请帮忙。

import socket
import mmap
from bluetooth import *
import msvcrt
import bluetooth
import pygame, time

from pygame.locals import *

pygame.mixer.pre_init(44100, 16, 2, 4096) #frequency, size, channels, buffersize
pygame.init() #turn all of pygame on.
DISPLAYSURF = pygame.display.set_mode((500, 400))
soundObj = pygame.mixer.Sound('sleep.wav')

target_name = "Joelk"
target_address = None

loop = False
isHome = False
playing = False

print("Press Esc to end....")
while loop == False:
    print("Perfoming Enquire")

    if msvcrt.kbhit():
        if ord(msvcrt.getch()) == 27:
            break
   nearby_devices = discover_devices(lookup_names = True)
print ("found %d devices" % len(nearby_devices))

if 0 == len(nearby_devices):
    print("There is no device nearby")
else:
    print("There is a device")
    for name, addr in nearby_devices:
        print (" %s - %s" % (addr, name))
        if "Joelk" == addr:
            isHome = True

    if(isHome == True):
        if(playing == True):
            print("Playing")
        else:
            soundObj.play()
            playing = True
    else:
        isHome = False
        soundObj.stop()
        print("Not Playing")

您永远不会在主循环中将 is_home 设置为 False。对 False 的唯一赋值发生在 else 分支中,该分支仅在当且仅当 is_homeFalse 时才执行,因此该语句无效。

如果未检测到合适的蓝牙设备,则必须将其设置为 false。这可以借助 break 和检测到的设备上 for 循环上的 else 子句来完成。

没有所有不必要的导入,没有星号导入,没有不必要的名字,没有不必要的括号和与 bool 文字的比较,并且未经测试:

import pygame
from bluetooth import discover_devices


def main():
    pygame.mixer.pre_init(44100, 16, 2, 4096)
    pygame.init()
    _display = pygame.display.set_mode((500, 400))
    sound = pygame.mixer.Sound('sleep.wav')

    is_home = False
    print('Press Esc to end....')
    while True:
        print('Performing Enquire')

        for event in pygame.event.get():
            if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
                break

        nearby_devices = discover_devices(lookup_names=True)
        print('found {0} devices'.format(len(nearby_devices)))
        if nearby_devices:
            for address, name in nearby_devices:
                print(' {0} - {1}'.format(address, name))
                if name == 'Joelk':
                    is_home = True
                    break
            else:
                is_home = False

            if is_home:
                if sound.get_num_channels() > 0:
                    print('Playing')
                else:
                    sound.play()
            else:
                sound.stop()
                print('Not Playing')


if __name__ == '__main__':
    main()

playing 标志被查询 Sound 对象当前正在播放的频道数所取代。如果你希望声音在无缝循环中播放,你应该看看 play() 方法关于循环声音的可选参数。