How to play a sound when my bluetooth device is detected
Question: Started with python programming this morning and wanted to make a simple
application that sniffs my phone's Bluetooth when I am around and play a song.
This app continues to search for my bluetooth every 27 seconds. If I am still
around, it will continue playing but I leave or switch off my bluetooth, I
want it to stop the song. I have the following code, everything works fine but
I get an error that stops the execution if there is no bluetooth device
detected and when I leave or switch off my device, the song continues to play.
Please help.

    
    
    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")
    


Answer: You never set `is_home` to `False` within the main loop. The only assignment
to `False` happens in an `else` branch that is only executed iff `is_home` was
`False` anyway so this statement has no effect.

It has to be set to false if no suitable bluetooth device is detected. This
can be done with the help of `break` and an `else` clause on the `for` loop
over the detected devices.

Without all the unnecessary imports, without star imports, without unnecessary
names, without unnecessary parenthesis and comparisons to `bool` literals, and
untested:

    
    
    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()
    

The `playing` flag was replaced by querying the `Sound` object on how many
channels it is currently playing. If you wand the sound playing in a gapless
loop you should have a look at the optional arguments of the `play()` method
regarding looping the sound.

