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

2024-10-02 00:38:58 发布

您现在位置:Python中文网/ 问答频道 /正文

今天早上从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")

Tags: nameimportfalsetrueifpygameelseaddr
1条回答
网友
1楼 · 发布于 2024-10-02 00:38:58

您永远不会在主循环中将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()方法关于循环声音的可选参数。在

相关问题 更多 >

    热门问题