Add Audio to PowerPoint in Java

·

2 min read

In PowerPoint documents, adding audio such as music, voiceovers, or sound effects to your slides is a great way to make your document creative and appealing. This article will share how to insert an audio file (.wav) into a presentation slide using Free Spire.Presentation for Java.

Import Dependency (2 Methods)

● Download the free library and unzip it, and then add the Spire.Presentation.jar file to your project as dependency.

● Directly add the jar dependency to your maven project by adding the following configurations to the pom.xml.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.presentation.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Sample Code

With Free Spire.Presentation for Java, you are allowed to get a specified slide where you want to insert audio using Presentation.getSlides().get() method, then you can inset a .wav audio file into the slide using ISlide.getShapes().appendAudioMedia(java.lang.String filePath, java.awt.geom.Rectangle2D rectangle) method.

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class InsertAudio {

    public static void main(String[] args) throws Exception {

        //Create a Presentation object and load a sample PowerPoint file
        Presentation presentation = new Presentation();
        presentation.loadFromFile("test.pptx");

        //Add a shape to the first slide
        Rectangle2D.Double labelRect= new Rectangle2D.Double(60, 50, 100, 50);
        IAutoShape labelShape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, labelRect);
        labelShape.getLine().setFillType(FillFormatType.NONE);
        labelShape.getFill().setFillType(FillFormatType.NONE);
        labelShape.getTextFrame().setText("Audio:");
        labelShape.getTextFrame().getTextRange().setFontHeight(28);
        labelShape.getTextFrame().getTextRange().setLatinFont(new TextFont("Arial"));
        labelShape.getTextFrame().getTextRange().getFill().setFillType(FillFormatType.SOLID);
        labelShape.getTextFrame().getTextRange().getFill().getSolidColor().setColor(Color.BLACK);

        //Append an audio file to the slide
        Rectangle2D.Double audioRect = new Rectangle2D.Double(160, 52, 50, 50);
        presentation.getSlides().get(0).getShapes().appendAudioMedia((new java.io.File("Music.wav")).getAbsolutePath(), audioRect);

        //Save to file
        presentation.saveToFile("InsertAudio.pptx", FileFormat.PPTX_2010);
        presentation.dispose();
    }
}

InsertAudio.png