Skip to content

Instantly share code, notes, and snippets.

@PierrickKoch
Created June 12, 2013 10:34
Show Gist options
  • Select an option

  • Save PierrickKoch/5764290 to your computer and use it in GitHub Desktop.

Select an option

Save PierrickKoch/5764290 to your computer and use it in GitHub Desktop.
import bpy
filepath = '/home/pkoch/media/music/Alice Russell/06 Lights Went Out.mp3'
# use an Empty here, since appending sound on a moving Cube gets wired (accel?)
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.object.empty_add()
# open sound
bpy.ops.sound.open(filepath=filepath)
sound = bpy.data.sounds[-1]
# add actuator
bpy.ops.logic.actuator_add(type='SOUND')
actuator = bpy.context.object.game.actuators[-1]
actuator.use_sound_3d = True
actuator.sound = sound
# add sensor
bpy.ops.logic.sensor_add(type='KEYBOARD')
sensor = bpy.context.object.game.sensors[-1]
sensor.key = 'SPACE'
# add controller
bpy.ops.logic.controller_add(type='LOGIC_AND')
controller = bpy.context.object.game.controllers[-1]
# link
controller.link(sensor=sensor, actuator=actuator)
# add Python controller
bpy.ops.logic.controller_add(type='PYTHON')
controller = bpy.context.object.game.controllers[-1]
# add text
bpy.ops.text.new()
text = bpy.data.texts[-1]
text.name = 'test.py'
text.write("""
cont = bge.logic.getCurrentController()
actuator = cont.actuators[-1]
obj = cont.owner
if obj['playing']:
actuator.pauseSound()
else:
actuator.startSound()
obj['playing'] = not obj['playing']
""")
controller.text = text
# link
controller.link(sensor=sensor, actuator=actuator)
# add property
bpy.ops.object.game_property_new(type='BOOL', name='playing')
playing = bpy.context.object.game.properties[-1]
playing.value = True
# motion
def key_loc(key, offset_location):
bpy.ops.logic.sensor_add(type='KEYBOARD')
sensor = bpy.context.object.game.sensors[-1]
sensor.key = key
bpy.ops.logic.actuator_add(type='MOTION')
actuator = bpy.context.object.game.actuators[-1]
actuator.offset_location = offset_location
bpy.ops.logic.controller_add(type='LOGIC_AND')
controller = bpy.context.object.game.controllers[-1]
controller.link(sensor=sensor, actuator=actuator)
key_loc('LEFT_ARROW', (0, +1, 0))
key_loc('RIGHT_ARROW', (0, -1, 0))
bpy.data.objects['Cube'].parent = bpy.context.object
# usage: blender -P blender_3D_startSound.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment