如何通过C#程序代码替换PPT幻灯片中的视频、音频文件
PPT幻灯片中支持插入视频及音频使幻灯片播放更形象生动,信息传递更具体。对PPT文档中已插入的视频、音频可执行读取、替换等操作。本文以C#和VB.NET程序代码介绍如何来实现文件替换。
程序环境:引入Spire.Presentation.dll 版本:Pack hotfix 6.2.2;Framework 4.5.1
实现效果如下图,在替换原有视频、音频文件时,也替换了原有视频封面、音频形状颜色等:
【C#】
using Spire.Presentation;
using Spire.Presentation.Collections;
using Spire.Presentation.Drawing;
using System.Drawing;
using System.IO;
namespace ReplaceVideo
{
class Program
{
static void Main(string[] args)
{
//加载PPT文档
Presentation ppt = new Presentation();
ppt.LoadFromFile("test.pptx");
//获取视频、音频文件集合
VideoCollection videos = ppt.Videos;
WavAudioCollection audios = ppt.WavAudios;
//遍历所有幻灯片
foreach (ISlide slide in ppt.Slides)
{
//遍历幻灯片中的所有形状
foreach (Shape shape in slide.Shapes)
{
//替换视频文件
if (shape is IVideo)
{
IVideo video = shape as IVideo;
byte[] bts = File.ReadAllBytes("newVideo.mp4");
VideoData videoData = videos.Append(bts);
video.EmbeddedVideoData = videoData;
Image image = Image.FromFile("jds.png");//加载图片
IImageData coverImage = ppt.Images.Append(image);
video.EmbedImage = coverImage;//设置视频封面图片
}
//替换音频文件
if(shape is IAudio)
{
IAudio audio = shape as IAudio;
byte[] bts1 = File.ReadAllBytes("newAudio.mp3");
IAudioData audiodata = audios.Append(bts1);
audio.Data = audiodata;
audio.Fill.SolidColor.Color = Color.GreenYellow;
}
}
}
//保存文档
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013);
System.Diagnostics.Process.Start("result.pptx");
}
}
}
【VB.NET】
Imports Spire.Presentation
Imports Spire.Presentation.Collections
Imports Spire.Presentation.Drawing
Imports System.Drawing
Imports System.IO
Namespace ReplaceVideo
Class Program
Private Shared Sub Main(args As String())
'加载PPT文档
Dim ppt As New Presentation()
ppt.LoadFromFile("test.pptx")
'获取视频、音频文件集合
Dim videos As VideoCollection = ppt.Videos
Dim audios As WavAudioCollection = ppt.WavAudios
'遍历所有幻灯片
For Each slide As ISlide In ppt.Slides
'遍历幻灯片中的所有形状
For Each shape As Shape In slide.Shapes
'替换视频文件
If TypeOf shape Is IVideo Then
Dim video As IVideo = TryCast(shape, IVideo)
Dim bts As Byte() = File.ReadAllBytes("newVideo.mp4")
Dim videoData As VideoData = videos.Append(bts)
video.EmbeddedVideoData = videoData
Dim image__1 As Image = Image.FromFile("jds.png")
'加载图片
Dim coverImage As IImageData = ppt.Images.Append(image__1)
'设置视频封面图片
video.EmbedImage = coverImage
End If
'替换音频文件
If TypeOf shape Is IAudio Then
Dim audio As IAudio = TryCast(shape, IAudio)
Dim bts1 As Byte() = File.ReadAllBytes("newAudio.mp3")
Dim audiodata As IAudioData = audios.Append(bts1)
audio.Data = audiodata
audio.Fill.SolidColor.Color = Color.GreenYellow
End If
Next
Next
'保存文档
ppt.SaveToFile("result.pptx", FileFormat.Pptx2013)
System.Diagnostics.Process.Start("result.pptx")
End Sub
End Class
End Namespace
注:代码中的文件路径是在VS项目文件夹下,如本次测试环境中的路径为:C:\Users\Administrator\Documents\Visual Studio 2013\Projects\VideoAndAudio_PPT\ReplaceVideoAndAudio_PPT\bin\Debug,文件路径也可以另外自行定义。放在项目文件夹下的话,对文件管理更为方便。