Tom
Tom

Reputation: 391

Bake sound to f curve on Geometry Node via Python API

I'm creating a script that loads a bunch of a audio files, for each audio file I want it to:

  1. Place the audio on the sequence
  2. Set the frames of the animation equal to the length of the audio
  3. Bake the audio to f curve on 2 different Geometry nodes. I'm very new to Blender and this is the state I expect via GUI:

enter image description here

  1. Render as animation

This is my code so far:

import bpy
import os

input_directory = ...
output_directory = ...

# Get a list of all audio files in the directory
audio_files = [file for file in os.listdir(input_directory) if file.endswith(".wav")][:1]

print(f"found {len(audio_files)} files to process")

# Set render settings
bpy.context.scene.render.image_settings.file_format = 'FFMPEG'
bpy.context.scene.render.ffmpeg.format = 'MPEG4'
bpy.context.scene.render.ffmpeg.audio_codec = 'AAC'

bpy.context.area.type = 'SEQUENCE_EDITOR'

def bake_node(node_name, audio_path):
    bpy.context.area.type = 'NODE_EDITOR'
    bpy.context.space_data.tree_type = 'GeometryNodeTree'
    
    if bpy.context.space_data.node_tree:
        node = bpy.context.space_data.node_tree.nodes.get(node_name)
        
        if node:
            print('found node: ', node)
            bpy.context.space_data.node_tree.nodes.active = node
            bpy.context.area.type = 'GRAPH_EDITOR'
            bpy.context.view_layer.objects.active = node
            bpy.ops.graph.sound_bake(filepath=audio_path, low=1, high=250, bake=True)
    else:
        print("Node tree not found in the Geometry Nodes workspace.")
        

# Loop through each audio file and load it into the sequencer
for idx, audio_file in enumerate(audio_files):
    # Add an audio strip to the sequencer
    audio_path = filepath=os.path.join(input_directory, audio_file)
    bpy.ops.sequencer.sound_strip_add(audio_path, frame_start=1, channel=1)
    
    bake_node("bake_target_2", audio_path)
    output_filename = f"animation_{audio_file}_{idx+1}.mp4"
    

    # Render the animation
    # bpy.context.scene.render.filepath = os.path.join(output_directory, output_filename)
    # bpy.ops.render.render(animation=True, write_still=True)

    # Remove the audio strip from the sequencer
    bpy.ops.sequencer.delete()

So far I've found the docs pretty useless and there's no clear path forward. Maybe some help explaining how the api maps to graphical elements?

Upvotes: 0

Views: 45

Answers (0)

Related Questions