3
$\begingroup$

I am trying to import and set the sound of a freshly created speaker using Python. Strangely the sound plays normally when I import it manually, but when I use Python to do the same thing it does not. Even when imported via script, the sound still shows up normally in the speaker-menu. This is my code:

bpy.ops.object.speaker_add()
bpy.ops.sound.open_mono(filepath=my_file_path)
bpy.data.speakers["Speaker"].sound = bpy.data.sounds[os.path.basename(path)]

I have made sure my file path is correct.

$\endgroup$
2
  • $\begingroup$ Good question! When adding the speaker using the add menu, Blender adds a NLA Track as well. However, I'm not sure why there is no option to set that up automatically. $\endgroup$
    – brockmann
    Apr 8 '20 at 14:53
  • $\begingroup$ Actually it adds an NLA track in - and I've also tried to delete that and add one in manually but that doesn't work either. $\endgroup$
    – GreenJoFlo
    Apr 9 '20 at 8:41
1
$\begingroup$

If my_file_path is a relative path, use the absolute file path instead.

Be aware that bpy.ops.sound.open_mono gives no warning or error message even if the audio file is not found (or does not exist). The sound still shows up normally in the speaker-menu but you can't hear anything.

I also had to call update_tag() and relink the speaker to the collection. I have no clue why this is necessary, but the following code works in Blender 2.83:

my_file_path = "/absoulute/path/to/test.mp3"
bpy.ops.object.speaker_add()
speaker = bpy.context.object
speaker.data.sound = bpy.data.sounds.load(my_file_path)
speaker.data.update_tag()
bpy.context.collection.objects.unlink(speaker)
bpy.context.collection.objects.link(speaker)
$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.