import bpy

#the sound file that will be used in the laughing sumilation
bpy.sound_filepath = "C:/Users/Jordi/Documents/UU/THESIS/Laughter_Sounds/harro2.mp3"


print('\n\n----------------------------\nSTARTING LAUGHING SIMULATION\n\n')

#check if we can set the type of mode in the 3dview
if bpy.ops.object.mode_set.poll():
    #switch to object mode so we can select the armature
    bpy.ops.object.mode_set(mode='OBJECT')
    #deselect all objects
    bpy.ops.object.select_all(action='DESELECT')
    #select the armature of the character
    bpy.ops.object.select_pattern(pattern="male_armature")
    bpy.context.scene.objects.active = bpy.data.objects["male_armature"]
    #since the armature is selected, we can set it to pose mode
    bpy.ops.object.mode_set(mode='POSE')
    #deselect all bones
    bpy.ops.pose.select_all(action='DESELECT')
    #select the driver bone on wich the sound will be baked
    bpy.ops.object.select_pattern(pattern="Driver")    
    #insert a keyframe so we get an fcurve on which we can bake the sound
    bpy.ops.anim.keyframe_insert_menu(type="Scaling")
    
    #change to graph editor view to be able to call the sound_bake function
    bpy.context.area.type = 'GRAPH_EDITOR'
    #go to frame 1 to prevent the sound to be baked from the wrong starting position
    bpy.ops.graph.cursor_set(frame=1)
    #bake the sound file as specified in the top of this script
    bpy.ops.graph.sound_bake(filepath=bpy.sound_filepath)
    
    print('Sound baked to driver...')
    #go back to text editor view for our own convenience
    bpy.context.area.type = 'TEXT_EDITOR'
    
    #switch back to object mode so we can start the game engine
    bpy.ops.object.mode_set(mode='OBJECT')
    
    #start the game engine
    bpy.ops.view3d.game_start()