Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically play the sound of a shape in PowerPoint

I am working on a PowerPoint 2007 VSTO add-in, and I am running in a small issue. The add-in adds sounds to the current slide using the following code:

var shape = slide.Shapes.AddMediaObject(soundFileLocation, 50, 50, 20, 20);

The resulting shape does have a sound, and can be played through the PowerPoint slide. My problem is that, given a reference to a shape that has been created that way, I would like to programmatically play the sound, but I can't find the way to do it. I tried

var soundEffect = shape.AnimationSettings.SoundEffect;
soundEffect.Play();

but this fails/crashes, and when I check soundEffect, its type is ppSoundNone.
Edit: got some partial success with

var shape = slide.Shapes.AddMediaObject(fileLocation, 50, 50, 20, 20);
shape.AnimationSettings.SoundEffect.ImportFromFile(fileLocation);

Doing this allows me to play the sound with:

var animationSettings = shape.AnimationSettings;
var soundEffect = shape.AnimationSettings.SoundEffect;
soundEffect.Play();

However there is one major issue; this works only for the last shape added. For some reason, shape.AnimationSettings.SoundEffect.ImportFromFile(fileLocation) seems to reset the SoundEffect property to ppSoundNone for the shapes previously created...

I would be surprised if this wasn't feasible, but I can't seem to find how - any help would be much appreciated!

like image 640
Mathias Avatar asked Jul 30 '10 23:07

Mathias


Video Answer


1 Answers

Sorry for the VBA, but it can easily be ported to C#. Here's what will work:

Sub addsound1()
    Dim ap As Presentation : Set ap = ActivePresentation
    Dim sl As Slide : Set sl = ap.Slides(1)
    Dim audioShape As Shape
    soundFileLocation = "C:\droid_scan.wav"
    Set audioShape = sl.Shapes.AddShape(msoShapeActionButtonSound, 100, 100, 50, 50)
    With audioShape.ActionSettings(ppMouseClick)
        .Action = ppActionNone
        .SoundEffect.ImportFromFile soundFileLocation
    End With
End Sub
Sub addsound2()
    Dim ap As Presentation : Set ap = ActivePresentation
    Dim sl As Slide : Set sl = ap.Slides(1)
    Dim audioShape As Shape
    soundFileLocation = "C:\droid_scan2.wav"
    Set audioShape = sl.Shapes.AddShape(msoShapeActionButtonSound, 50, 50, 50, 50)
    With audioShape.ActionSettings(ppMouseClick)
        .Action = ppActionNone
        .SoundEffect.ImportFromFile soundFileLocation
    End With
End Sub

Sub PlaySound1()
    Dim sh As Shape
    Set sh = ActivePresentation.Slides(1).Shapes(1)
    sh.ActionSettings(ppMouseClick).SoundEffect.Play
End Sub

Sub PlaySound2()
    Dim sh As Shape
    Set sh = ActivePresentation.Slides(1).Shapes(2)
    sh.ActionSettings(ppMouseClick).SoundEffect.Play
End Sub
like image 88
Todd Main Avatar answered Oct 20 '22 12:10

Todd Main