bl_info = { 
    "name": "Browser Sound Player",
    "location": "Filebrowser > Left Panel > Browser Sound Player",
    "category": "Filebrowser",
    "blender": (2, 90, 0),
    "author": "Gregory Smirnov"
}



import bpy
from bpy.types import Panel

### Variables

fileplay = ''
rewind = 5
rewind_operator = 'UP'  #'UP' or 'DOWN'


### Functions

#____________________________________________________________________________________________

def playSound():
    
    '''Play selected sound'''
    
    import aud    
    
    selectedFile = ''
    for screenArea in bpy.context.window.screen.areas:
       if screenArea.type == 'FILE_BROWSER':
            params = screenArea.spaces[0].params
            dir = params.directory
            filename = params.filename
            dir = dir.decode('UTF-8')
            selectedFile = dir+filename
            break
        
    print('\n')  
    print(selectedFile) 


    try:

        sound = aud.Sound.file(selectedFile)
        
        if bpy.context.scene.sound_cache: sound = sound.cache()
            
        
        print(sound.data())
        
        device = aud.Device()
        device.stopAll()

        play = device.play(sound) 


        device.volume = bpy.context.scene.sound_volume*0.01
       
        
    except:
        print('File not sound')
        
    return filename          


#__________________________________________________________________________________________

def stopSound():
    
    '''Stop playing sound'''
    
    import aud

    device = aud.Device()
    device.stopAll()
 
 
#__________________________________________________________________________________________    
    
    
def rewindSound():
    
    '''Rewind selected sound'''
    
    import aud
    
    global rewind
    global rewind_operator
    
    selectedFile = ''
    for screenArea in bpy.context.window.screen.areas:
       if screenArea.type == 'FILE_BROWSER':
            params = screenArea.spaces[0].params
            dir = params.directory
            filename = params.filename
            dir = dir.decode('UTF-8')
            selectedFile = dir+filename
            break
        
    print('\n')  
    print(selectedFile) 


    try:

        sound = aud.Sound.file(selectedFile)
        
        if bpy.context.scene.sound_cache: sound = sound.cache()
        
            
        sound = sound.limit(rewind, 100.0)
        
        
        if rewind_operator == 'UP':        
                rewind += 5
                
        if rewind_operator == 'DOWN':        
                rewind -= 5  
                
        if rewind < 0: rewind = 0                      
        

        
        print(sound.data())
        
        device = aud.Device()
        device.stopAll()

        play = device.play(sound) 


        device.volume = bpy.context.scene.sound_volume*0.01
       
        
    except:
        print('File not sound')
        
    return filename  


#______________________________________________________________________________________________ 
    
    
def updateVolume(self, context): 
    
    '''Change volume by property'''
    
    import aud
    
    device = aud.Device()
    device.volume = self.sound_volume*0.01
      


### Main UI

class FILEBROWSER_PT_sound(Panel):
    bl_space_type = 'FILE_BROWSER'
    bl_region_type = 'TOOLS'
    #bl_region_type = 'UI'
    bl_label = "Directory Path"
    bl_category = "Attributes"
    bl_options = {'HIDE_HEADER'}



    def draw(self, context):
        layout = self.layout
        
        #pre_info = layout.row()        
        sets = layout.column() 
        info = layout.row()                
        rew = layout.row(align=True)        
        play = layout.row(align=True)        
                
        
        
        #pre_info.label(text="Browser Sound Player 1.0")
        play.operator("stop.play", text="Stop", icon='MUTE_IPO_OFF') 
        play.operator("sound.revdown", text="", icon='TRIA_LEFT_BAR')  
        play.operator("sound.revup", text="", icon='TRIA_RIGHT_BAR')                              
        play.operator("sound.play", text="Play", icon='PLAY_SOUND')
        

        sets.prop(context.scene, 'sound_cache', icon = 'MEMORY')               
        sets.prop(context.scene, 'sound_volume')
        
        info.label(text="Sound: "+fileplay)
        
        
### Buttons and properties        
        
        
class BUTTON_OP_play_sound(bpy.types.Operator):
    """Play selected sound"""
    bl_idname = "sound.play"
    bl_label = "Simple Object Operator"



    def execute(self, context):
        global fileplay
        fileplay = playSound()
        return {'FINISHED'} 
    
    
class BUTTON_OP_stop_sound(bpy.types.Operator):
    """Stop playing sound"""
    bl_idname = "stop.play"
    bl_label = "Jump up"



    def execute(self, context):
        global fileplay
        stopSound()
        fileplay = ''
        return {'FINISHED'}  
    
    
class BUTTON_OP_rewind_up(bpy.types.Operator):
    """Rewind sound up 5 second"""
    bl_idname = "sound.revup"
    bl_label = "Simple Object Operator"



    def execute(self, context):
        
        global fileplay
        global rewind_operator
        rewind_operator = 'UP'
        fileplay = rewindSound()
        
        return {'FINISHED'}   
    
    
class BUTTON_OP_rewind_down(bpy.types.Operator):
    """Rewind sound down 5 second"""
    bl_idname = "sound.revdown"
    bl_label = "Jump down"



    def execute(self, context):
        global fileplay
        global rewind_operator
        rewind_operator = 'DOWN'
        fileplay = rewindSound()
                
        return {'FINISHED'}      
    
    
       
    
    
### Register     
    
    
def register():
    bpy.utils.register_class(FILEBROWSER_PT_sound)
    bpy.utils.register_class(BUTTON_OP_play_sound)
    bpy.utils.register_class(BUTTON_OP_stop_sound)
    bpy.utils.register_class(BUTTON_OP_rewind_up)
    bpy.utils.register_class(BUTTON_OP_rewind_down)
    
    bpy.types.Scene.sound_volume = bpy.props.IntProperty(name='Volume', default=50, max=100, min = 3, subtype='PERCENTAGE', update=updateVolume )   
    bpy.types.Scene.sound_cache = bpy.props.BoolProperty(name='RAM Cache', default=False, description='Cache sound to RAM')   


def unregister():
    bpy.utils.unregister_class(FILEBROWSER_PT_sound)
    bpy.utils.unregister_class(BUTTON_OP_play_sound)
    bpy.utils.unregister_class(BUTTON_OP_stop_sound)
    bpy.utils.unregister_class(BUTTON_OP_rewind_up)
    bpy.utils.unregister_class(BUTTON_OP_rewind_down)      
    
    del bpy.types.Scene.sound_volume
    del bpy.types.Scene.sound_cache

if __name__ == "__main__":
    register()           



