今天早上从python编程开始,我想做一个简单的应用程序,当我在附近播放一首歌时,它可以嗅出我手机的蓝牙。此应用程序每隔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_home
为False
时执行,因此该语句没有任何效果。在如果没有检测到合适的蓝牙设备,则必须将其设置为false。这可以通过
break
和检测到的设备上的for
循环上的else
子句来完成。在没有所有不必要的导入,没有星型导入,没有不必要的名称,没有不必要的括号和与
bool
字面值的比较,并且未经测试:playing
标志被替换为查询Sound
对象当前播放的频道数。如果你想让声音在无间隙循环中播放,你应该看看play()
方法关于循环声音的可选参数。在相关问题 更多 >
编程相关推荐