2
$\begingroup$

I haven't been able to figure out the context and the bpy.ops failures from bad context yet.

Here is a new one. I open Blender -> New -> Video Editing. Sequencer view appears in the new Video Editing workspace at the bottom of the screen. In Sequencer view panel click buttons Add -> Sound. Sound appears in Sequencer. Grab this line of code from the Scripting workspace tab (addable with the + in the top ribbon menu).

bpy.ops.sequencer.sound_strip_add(filepath="//audio/export/session.flac", directory="/fake/path/audio/export/", files=[{"name":"session.flac", "name":"session.flac"}], relative_path=True, frame_start=1, channel=1)

Go ahead and copy that line of code. Run it in the Python console in the Scripting workspace or in new Text of the Text panel in the Scripting workspace. Same error either way:

RuntimeError: Operator bpy.ops.sequencer.sound_strip_add.poll() failed, context is incorrect

Try a third way? Will see that same error at startup like ./blender --python yourScript.py and the script will fail.

$\endgroup$
1

1 Answer 1

2
$\begingroup$

Similar to https://blender.stackexchange.com/a/247799/86891

You need to override the context with the correct area, this operator is meant to be run in the context of the video sequencer area. You can run the script using a simple override if you have an open VSE or temporarily create one to run the operator if you don't.

import bpy


def override_sound_strip_add(area):
    with bpy.context.temp_override(area=area):
        bpy.ops.sequencer.sound_strip_add(filepath=filepath, frame_start=1, channel=1)  
    

filepath = r"path\to\your\audio.wav"


try:  # Assume we have a video sequence editor open
    area_editor = next((a for a in bpy.context.screen.areas if a.type == "SEQUENCE_EDITOR"))
    override_sound_strip_add(area_editor)
except StopIteration:  # We don't have a video sequence editor open
    area = bpy.context.screen.areas[0]
    old_type = area.type  # Store the overriden area type to set it back later
    area.type = "SEQUENCE_EDITOR"
    override_sound_strip_add(area)
    area.type = old_type  # Restore the area type

See A comprehensive list of operator overrides for a further list of operator overrides.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .