今天早上开始使用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")
答案 0 :(得分:1)
您从未在主循环中将is_home
设置为False
。对False
的唯一分配发生在else
分支中,只有当is_home
False
为break
时才会执行,因此此语句无效。
如果未检测到合适的蓝牙设备,则必须设置为false。这可以通过else
的帮助和for
循环检测设备上的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()
对象查询当前正在播放的频道数。如果您在无间隙循环中演奏声音,您应该查看有关循环声音的int i1,i2;
....
方法的可选参数。