Skip to content

Commit ba3dd72

Browse files
authored
Add audio (#335)
1 parent 4986e62 commit ba3dd72

File tree

6 files changed

+1710
-0
lines changed

6 files changed

+1710
-0
lines changed
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
---
2+
3+
api_name:
4+
- Microsoft.Office.DocumentFormat.OpenXML.Packaging
5+
api_type:
6+
- schema
7+
ms.assetid: 0265732e-d81a-4654-b0ba-d9d87e544f7c
8+
title: 'How to: Add an audio file to a slide in a presentation'
9+
ms.suite: office
10+
11+
ms.author: o365devx
12+
author: o365devx
13+
ms.topic: conceptual
14+
ms.date: 03/31/2025
15+
ms.localizationpriority: medium
16+
---
17+
18+
# Add an audio file to a slide in a presentation
19+
20+
This topic shows how to use the classes in the Open XML SDK for
21+
Office to add an audio file to the last slide in a presentation
22+
programmatically.
23+
24+
## Getting a Presentation Object
25+
26+
In the Open XML SDK, the <xref:DocumentFormat.OpenXml.Packaging.PresentationDocument> class represents a presentation document package. To work with a presentation document,
27+
first create an instance of the `PresentationDocument` class, and then work with
28+
that instance. To create the class instance from the document call the <xref:DocumentFormat.OpenXml.Packaging.PresentationDocument.Open*> method that uses a file path, and a
29+
Boolean value as the second parameter to specify whether a document is editable. To open a document for read/write, specify the value `true` for this parameter as shown in the following
30+
`using` statement. In this code, the file parameter is a string that represents the path for the file from which you want to open the document.
31+
32+
### [C#](#tab/cs-1)
33+
[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet1)]
34+
35+
### [Visual Basic](#tab/vb-1)
36+
[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet1)]
37+
***
38+
39+
40+
[!include[Using Statement](../includes/presentation/using-statement.md)] `ppt`.
41+
42+
43+
## The Structure of the Audio From File
44+
45+
The PresentationML document consists of a number of parts, among which is the Picture (`<pic/>`) element.
46+
47+
The following text from the [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)] specification introduces the overall form of a `PresentationML` package.
48+
49+
Audio File (`<audioFile/>`) specifies the presence of an audio file. This element is specified within the non-visual properties of an object. The audio shall be attached to an object as this is how it is represented within the document. The actual playing of the audio however is done within the timing node list that is specified under the timing element.
50+
51+
Consider the following ``Picture`` object that has an audio file attached to it.
52+
53+
```xml
54+
<p:pic>
55+
<p:nvPicPr>
56+
<p:cNvPr id="7" name="Rectangle 6">
57+
<a:hlinkClick r:id="" action="ppaction://media"/>
58+
</p:cNvPr>
59+
<p:cNvPicPr>
60+
<a:picLocks noRot="1"/>
61+
</p:cNvPicPr>
62+
<p:nvPr>
63+
<a:audioFile r:link="rId1"/>
64+
</p:nvPr>
65+
</p:nvPicPr>
66+
</p:pic>
67+
```
68+
69+
In the above example, we see that there is a single audioFile element attached to this picture. This picture is placed within the document just as a normal picture or shape would be. The id of this picture, namely 7 in this case, is used to refer to this audioFile element from within the timing node list. The Linked relationship id is used to retrieve the actual audio file for playback purposes.
70+
71+
&copy; [!include[ISO/IEC 29500 version](../includes/iso-iec-29500-version.md)]
72+
73+
The following XML Schema fragment defines the contents of audioFile.
74+
75+
```xml
76+
<xsd:complexType name="CT_TLMediaNodeAudio">
77+
<xsd:sequence>
78+
<xsd:element name="cMediaNode" type="CT_TLCommonMediaNodeData" minOccurs="1" maxOccurs="1"/>
79+
</xsd:sequence>
80+
<xsd:attribute name="isNarration" type="xsd:boolean" use="optional" default="false"/>
81+
</xsd:complexType>
82+
```
83+
84+
## How the Sample Code Works
85+
86+
After opening the presentation file for read/write access in the `using` statement, the code gets the presentation
87+
part from the presentation document. Then it gets the relationship ID of
88+
the last slide, and gets the slide part from the relationship ID.
89+
90+
91+
### [C#](#tab/cs-2)
92+
[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet2)]
93+
94+
### [Visual Basic](#tab/vb-2)
95+
[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet2)]
96+
***
97+
98+
The code first creates a media data part for the audio file to be added. With the audio file stream open, it feeds the media data part object. Next, audio and media relationship references are added to the slide using the provided embedId for future reference to the audio file and mediaEmbedId for media reference.
99+
100+
An image part is then added with a sample picture to be used as a placeholder for the audio. A picture object is created with various elements, such as Non-Visual Drawing Properties (`<cNvPr/>`), which specify non-visual canvas properties. This allows for additional information that does not affect the appearance of the picture to be stored. The `<audioFile/>` element, explained above, is also included. The HyperLinkOnClick (`<hlinkClick/>`) element specifies the on-click hyperlink information to be applied to a run of text or image. When the hyperlink text or image is clicked, the link is fetched. Non-Visual Picture Drawing Properties (`<cNvPicPr/>`) specify the non-visual properties for the picture canvas. For a detailed explanation of the elements used, please refer to [!include[ISO/IEC 29500 URL](../includes/iso-iec-29500-link.md)]
101+
102+
### [C#](#tab/cs-3)
103+
[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet3)]
104+
105+
### [Visual Basic](#tab/vb-3)
106+
[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet3)]
107+
***
108+
109+
Next the Media(CT_Media) element is created with use of the previously referenced mediaEmbedId(Embedded Picture Reference). The Blip element is also added; this element specifies the existence of an image (binary large image or picture) and contains a reference to the image data. Blip's Embed attribute is used to specify an placeholder image in the Image Part created previously.
110+
111+
### [C#](#tab/cs-4)
112+
[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet4)]
113+
114+
### [Visual Basic](#tab/vb-4)
115+
[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet4)]
116+
***
117+
118+
All other elements such as Offset(`<off/>`), Stretch(`<stretch/>`), fillRectangle(`<fillRect/>`), are appended to the ShapeProperties(`<spPr/>`) and ShapeProperties are appended to the Picture element(`<pic/>`). Finally the picture element that includes audio is added to the ShapeTree(`<sp/>`) of the slide.
119+
120+
Following is the complete sample code that you can use to add audio to the slide.
121+
122+
## Sample Code
123+
124+
### [C#](#tab/cs)
125+
[!code-csharp[](../../samples/presentation/add_audio/cs/Program.cs#snippet0)]
126+
127+
### [Visual Basic](#tab/vb)
128+
[!code-vb[](../../samples/presentation/add_audio/vb/Program.vb#snippet0)]
129+
***
130+
131+
## See also
132+
133+
- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk)
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
using DocumentFormat.OpenXml;
2+
using DocumentFormat.OpenXml.Presentation;
3+
using A = DocumentFormat.OpenXml.Drawing;
4+
using P14 = DocumentFormat.OpenXml.Office2010.PowerPoint;
5+
using ShapeTree = DocumentFormat.OpenXml.Presentation.ShapeTree;
6+
using ShapeProperties = DocumentFormat.OpenXml.Presentation.ShapeProperties;
7+
using NonVisualDrawingProperties = DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties;
8+
using NonVisualPictureProperties = DocumentFormat.OpenXml.Presentation.NonVisualPictureProperties;
9+
using NonVisualPictureDrawingProperties = DocumentFormat.OpenXml.Presentation.NonVisualPictureDrawingProperties;
10+
using Picture = DocumentFormat.OpenXml.Presentation.Picture;
11+
using BlipFill = DocumentFormat.OpenXml.Presentation.BlipFill;
12+
using DocumentFormat.OpenXml.Packaging;
13+
using ApplicationNonVisualDrawingProperties = DocumentFormat.OpenXml.Presentation.ApplicationNonVisualDrawingProperties;
14+
using System.IO;
15+
using System.Linq;
16+
using System;
17+
18+
// <Snippet0>
19+
AddAudio(args[0], args[1], args[2]);
20+
21+
static void AddAudio(string filePath, string audioFilePath, string coverPicPath)
22+
{
23+
24+
string imgEmbedId = "rId4", embedId = "rId3", mediaEmbedId = "rId2";
25+
UInt32Value shapeId = 5;
26+
// <Snippet1>
27+
using (PresentationDocument presentationDocument = PresentationDocument.Open(filePath, true))
28+
// </Snippet1>
29+
{
30+
31+
if (presentationDocument.PresentationPart == null || presentationDocument.PresentationPart.Presentation.SlideIdList == null)
32+
{
33+
throw new NullReferenceException("Presentation Part is empty or there are no slides in it");
34+
}
35+
36+
// <Snippet2>
37+
//Get presentation part
38+
PresentationPart presentationPart = presentationDocument.PresentationPart;
39+
40+
//Get slides ids.
41+
OpenXmlElementList slidesIds = presentationPart.Presentation.SlideIdList.ChildElements;
42+
43+
//Get relationsipId of the last slide
44+
string? audioSlidePartRelationshipId = ((SlideId)slidesIds[slidesIds.ToArray().Length - 1]).RelationshipId;
45+
46+
if (audioSlidePartRelationshipId == null)
47+
{
48+
throw new NullReferenceException("Slide id not found");
49+
}
50+
51+
//Get slide part by relationshipID
52+
SlidePart? slidePart = (SlidePart)presentationPart.GetPartById(audioSlidePartRelationshipId);
53+
// </Snippet2>
54+
55+
// <Snippet3>
56+
// Create audio Media Data Part (content type, extension)
57+
MediaDataPart mediaDataPart = presentationDocument.CreateMediaDataPart("audio/mp3", ".mp3");
58+
59+
//Get the audio file and feed the stream
60+
using (Stream mediaDataPartStream = File.OpenRead(audioFilePath))
61+
{
62+
mediaDataPart.FeedData(mediaDataPartStream);
63+
}
64+
//Adds a AudioReferenceRelationship to the MainDocumentPart
65+
slidePart.AddAudioReferenceRelationship(mediaDataPart, embedId);
66+
67+
//Adds a MediaReferenceRelationship to the SlideLayoutPart
68+
slidePart.AddMediaReferenceRelationship(mediaDataPart, mediaEmbedId);
69+
70+
NonVisualDrawingProperties nonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = shapeId, Name = "audio" };
71+
A.AudioFromFile audioFromFile = new A.AudioFromFile() { Link = embedId };
72+
73+
ApplicationNonVisualDrawingProperties appNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
74+
appNonVisualDrawingProperties.Append(audioFromFile);
75+
76+
//adds sample image to the slide with id to be used as reference in blip
77+
ImagePart imagePart = slidePart.AddImagePart(ImagePartType.Png, imgEmbedId);
78+
using (Stream data = File.OpenRead(coverPicPath))
79+
{
80+
imagePart.FeedData(data);
81+
}
82+
83+
if (slidePart!.Slide!.CommonSlideData!.ShapeTree == null)
84+
{
85+
throw new NullReferenceException("Presentation shape tree is empty");
86+
}
87+
88+
//Getting existing shape tree element from PowerPoint
89+
ShapeTree shapeTree = slidePart.Slide.CommonSlideData.ShapeTree;
90+
91+
// specifies the existence of a picture within a presentation.
92+
// It can have non-visual properties, a picture fill as well as shape properties attached to it.
93+
Picture picture = new Picture();
94+
NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties();
95+
96+
A.HyperlinkOnClick hyperlinkOnClick = new A.HyperlinkOnClick() { Id = "", Action = "ppaction://media" };
97+
nonVisualDrawingProperties.Append(hyperlinkOnClick);
98+
99+
NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties();
100+
A.PictureLocks pictureLocks = new A.PictureLocks() { NoChangeAspect = true };
101+
nonVisualPictureDrawingProperties.Append(pictureLocks);
102+
103+
ApplicationNonVisualDrawingPropertiesExtensionList appNonVisualDrawingPropertiesExtensionList = new ApplicationNonVisualDrawingPropertiesExtensionList();
104+
ApplicationNonVisualDrawingPropertiesExtension appNonVisualDrawingPropertiesExtension = new ApplicationNonVisualDrawingPropertiesExtension() { Uri = "{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}" };
105+
// </Snippet3>
106+
107+
// <Snippet4>
108+
P14.Media media = new() { Embed = mediaEmbedId };
109+
media.AddNamespaceDeclaration("p14", "http://schemas.microsoft.com/office/powerpoint/2010/main");
110+
111+
appNonVisualDrawingPropertiesExtension.Append(media);
112+
appNonVisualDrawingPropertiesExtensionList.Append(appNonVisualDrawingPropertiesExtension);
113+
appNonVisualDrawingProperties.Append(appNonVisualDrawingPropertiesExtensionList);
114+
115+
nonVisualPictureProperties.Append(nonVisualDrawingProperties);
116+
nonVisualPictureProperties.Append(nonVisualPictureDrawingProperties);
117+
nonVisualPictureProperties.Append(appNonVisualDrawingProperties);
118+
119+
//Prepare shape properties to display picture
120+
BlipFill blipFill = new BlipFill();
121+
A.Blip blip = new A.Blip() { Embed = imgEmbedId };
122+
// </Snippet4>
123+
124+
A.Stretch stretch = new A.Stretch();
125+
A.FillRectangle fillRectangle = new A.FillRectangle();
126+
A.Transform2D transform2D = new A.Transform2D();
127+
A.Offset offset = new A.Offset() { X = 1524000L, Y = 857250L };
128+
A.Extents extents = new A.Extents() { Cx = 9144000L, Cy = 5143500L };
129+
A.PresetGeometry presetGeometry = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle };
130+
A.AdjustValueList adjValueList = new A.AdjustValueList();
131+
132+
stretch.Append(fillRectangle);
133+
blipFill.Append(blip);
134+
blipFill.Append(stretch);
135+
transform2D.Append(offset);
136+
transform2D.Append(extents);
137+
presetGeometry.Append(adjValueList);
138+
139+
ShapeProperties shapeProperties = new ShapeProperties();
140+
shapeProperties.Append(transform2D);
141+
shapeProperties.Append(presetGeometry);
142+
143+
//adds all elements to the slide's shape tree
144+
picture.Append(nonVisualPictureProperties);
145+
picture.Append(blipFill);
146+
picture.Append(shapeProperties);
147+
148+
shapeTree.Append(picture);
149+
150+
}
151+
}
152+
// </Snippet0>
Binary file not shown.

0 commit comments

Comments
 (0)