Конвертировать презентации PowerPoint в видео на Android

Преобразовав вашу презентацию PowerPoint в видео, вы получаете

  • Increase in accessibility: Все устройства (независимо от платформы) по умолчанию оснащены видеоплеерами, в отличие от приложений для открытия презентаций, поэтому пользователям проще открывать или воспроизводить видео.
  • More reach: С помощью видео вы можете охватить большую аудиторию и донести до неё информацию, которая иначе могла бы показаться скучной в презентации. Большинство опросов и статистических данных свидетельствуют о том, что люди смотрят и потребляют видео больше, чем другие формы контента, и обычно предпочитают именно такой контент.

Преобразование PowerPoint в видео в Aspose.Slides

В Aspose.Slides 22.11 мы реализовали поддержку преобразования презентаций в видео.

  • Используйте Aspose.Slides для создания набора кадров (из слайдов презентации), соответствующих определённому FPS (кадров в секунду)
  • Используйте стороннюю утилиту, например ffmpeg (for java), чтобы собрать видео из этих кадров.

Convert PowerPoint to Video

  1. Add this to your POM file:
   <dependency>
     <groupId>net.bramp.ffmpeg</groupId>
     <artifactId>ffmpeg</artifactId>
     <version>0.7.0</version>
   </dependency>
  1. Download ffmpeg here.

  2. Run the PowerPoint to video Java code.

Этот Java‑код показывает, как преобразовать презентацию (с фигурой и двумя анимационными эффектами) в видео:

Presentation presentation = new Presentation();
try {
    // Добавляет форму смайлика и затем анимирует её
    IAutoShape smile = presentation.getSlides().get_Item(0).getShapes().addAutoShape(ShapeType.SmileyFace, 110, 20, 500, 500);
    ISequence mainSequence = presentation.getSlides().get_Item(0).getTimeline().getMainSequence();
    IEffect effectIn = mainSequence.addEffect(smile, EffectType.Fly, EffectSubtype.TopLeft, EffectTriggerType.AfterPrevious);
    IEffect effectOut = mainSequence.addEffect(smile, EffectType.Fly, EffectSubtype.BottomRight, EffectTriggerType.AfterPrevious);
    effectIn.getTiming().setDuration(2f);
    effectOut.setPresetClassType(EffectPresetClassType.Exit);

    final int fps = 33;
    ArrayList<String> frames = new ArrayList<String>();

    PresentationAnimationsGenerator animationsGenerator = new PresentationAnimationsGenerator(presentation);
    try
    {
        PresentationPlayer player = new PresentationPlayer(animationsGenerator, fps);
        try {
            player.setFrameTick((sender, arguments) ->
            {
                try {
                    String frame = String.format("frame_%04d.png", sender.getFrameIndex());
                    arguments.getFrame().save(frame, ImageFormat.Png);
                    frames.add(frame);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            animationsGenerator.run(presentation.getSlides());
        } finally {
            if (player != null) player.dispose();
        }
    } finally {
        if (animationsGenerator != null) animationsGenerator.dispose();
    }

    // Настройте папку с бинарниками ffmpeg. Смотрите эту страницу: https://github.com/rosenbjerg/FFMpegCore#installation
    FFmpeg ffmpeg = new FFmpeg("path/to/ffmpeg");
    FFprobe ffprobe = new FFprobe("path/to/ffprobe");

    FFmpegBuilder builder = new FFmpegBuilder()
            .addExtraArgs("-start_number", "1")
            .setInput("frame_%04d.png")
            .addOutput("output.avi")
            .setVideoFrameRate(FFmpeg.FPS_24)
            .setFormat("avi")
            .done();

    FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe);
    executor.createJob(builder).run();
} catch (IOException e) {
    e.printStackTrace();
}

Эффекты видео

Вы можете применять анимацию к объектам на слайдах и использовать переходы между слайдами.

Анимации и переходы делают слайд‑шоу более захватывающим и интересным — и то же самое происходит с видео. Добавим еще один слайд и переход в код предыдущей презентации:

// Добавляет форму смайлика и анимирует её

// ...

// Добавляет новый слайд и анимированный переход

ISlide newSlide = presentation.getSlides().addEmptySlide(presentation.getSlides().get_Item(0).getLayoutSlide());

newSlide.getBackground().setType(BackgroundType.OwnBackground);

newSlide.getBackground().getFillFormat().setFillType(FillType.Solid);

newSlide.getBackground().getFillFormat().getSolidFillColor().setColor(Color.MAGENTA);

newSlide.getSlideShowTransition().setType(TransitionType.Push);

Aspose.Slides также поддерживает анимацию текста. Мы анимируем абзацы на объектах, которые будут появляться последовательно (с задержкой в одну секунду):

Presentation presentation = new Presentation();
try {
    // Добавляет текст и анимацию
    IAutoShape autoShape = presentation.getSlides().get_Item(0).getShapes().addAutoShape(ShapeType.Rectangle, 210, 120, 300, 300);
    Paragraph para1 = new Paragraph();
    para1.getPortions().add(new Portion("Aspose Slides for Java"));
    Paragraph para2 = new Paragraph();
    para2.getPortions().add(new Portion("convert PowerPoint Presentation with text to video"));

    Paragraph para3 = new Paragraph();
    para3.getPortions().add(new Portion("paragraph by paragraph"));
    IParagraphCollection paragraphCollection = autoShape.getTextFrame().getParagraphs();
    paragraphCollection.add(para1);
    paragraphCollection.add(para2);
    paragraphCollection.add(para3);
    paragraphCollection.add(new Paragraph());

    ISequence mainSequence = presentation.getSlides().get_Item(0).getTimeline().getMainSequence();
    IEffect effect1 = mainSequence.addEffect(para1, EffectType.Appear, EffectSubtype.None, EffectTriggerType.AfterPrevious);
    IEffect effect2 = mainSequence.addEffect(para2, EffectType.Appear, EffectSubtype.None, EffectTriggerType.AfterPrevious);
    IEffect effect3 = mainSequence.addEffect(para3, EffectType.Appear, EffectSubtype.None, EffectTriggerType.AfterPrevious);
    IEffect effect4 = mainSequence.addEffect(para3, EffectType.Appear, EffectSubtype.None, EffectTriggerType.AfterPrevious);

    effect1.getTiming().setTriggerDelayTime(1f);
    effect2.getTiming().setTriggerDelayTime(1f);
    effect3.getTiming().setTriggerDelayTime(1f);
    effect4.getTiming().setTriggerDelayTime(1f);

    final int fps = 33;
    ArrayList<String> frames = new ArrayList<String>();

    PresentationAnimationsGenerator animationsGenerator = new PresentationAnimationsGenerator(presentation);
    try
    {
        PresentationPlayer player = new PresentationPlayer(animationsGenerator, fps);
        try {
            player.setFrameTick((sender, arguments) ->
            {
                try {
                    String frame = String.format("frame_%04d.png", sender.getFrameIndex());
                    arguments.getFrame().save(frame, ImageFormat.Png);
                    frames.add(frame);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            animationsGenerator.run(presentation.getSlides());
        } finally {
            if (player != null) player.dispose();
        }
    } finally {
        if (animationsGenerator != null) animationsGenerator.dispose();
    }

    // Настройте папку бинарных файлов ffmpeg. Смотрите эту страницу: https://github.com/rosenbjerg/FFMpegCore#installation
    FFmpeg ffmpeg = new FFmpeg("path/to/ffmpeg");
    FFprobe ffprobe = new FFprobe("path/to/ffprobe");

    FFmpegBuilder builder = new FFmpegBuilder()
            .addExtraArgs("-start_number", "1")
            .setInput("frame_%04d.png")
            .addOutput("output.avi")
            .setVideoFrameRate(FFmpeg.FPS_24)
            .setFormat("avi")
            .done();

    FFmpegExecutor executor = new FFmpegExecutor(ffmpeg, ffprobe);
    executor.createJob(builder).run();
} catch (IOException e) {
    e.printStackTrace();
}

Классы конвертации видео

Для выполнения задач по преобразованию PowerPoint в видео Aspose.Slides предоставляет классы PresentationAnimationsGenerator и PresentationPlayer.

PresentationAnimationsGenerator позволяет задать размер кадра для будущего видео через конструктор. Если передать экземпляр презентации, будет использован Presentation.SlideSize, и он генерирует анимации, которые использует PresentationPlayer.

При генерации анимаций для каждой последующей анимации генерируется событие NewAnimation с параметром IPresentationAnimationPlayer. Этот параметр — класс, представляющий проигрыватель отдельной анимации.

Для работы с IPresentationAnimationPlayer используется свойство Duration (полная длительность анимации) и метод SetTimePosition. Каждая позиция анимации задаётся в диапазоне 0 до duration, после чего метод GetFrame возвращает BufferedImage, соответствующий состоянию анимации в данный момент:

Presentation presentation = new Presentation();
try {
    // Добавляет форму смайлика и анимирует её
    IAutoShape smile = presentation.getSlides().get_Item(0).getShapes().addAutoShape(ShapeType.SmileyFace, 110, 20, 500, 500);
    ISequence mainSequence = presentation.getSlides().get_Item(0).getTimeline().getMainSequence();
    IEffect effectIn = mainSequence.addEffect(smile, EffectType.Fly, EffectSubtype.TopLeft, EffectTriggerType.AfterPrevious);
    IEffect effectOut = mainSequence.addEffect(smile, EffectType.Fly, EffectSubtype.BottomRight, EffectTriggerType.AfterPrevious);
    effectIn.getTiming().setDuration(2f);
    effectOut.setPresetClassType(EffectPresetClassType.Exit);

    PresentationAnimationsGenerator animationsGenerator = new PresentationAnimationsGenerator(presentation);
    try {
        animationsGenerator.setNewAnimation(animationPlayer ->
        {
            System.out.println(String.format("Animation total duration: %f", animationPlayer.getDuration()));
            animationPlayer.setTimePosition(0); // начальное состояние анимации
            try {
                // растровое изображение начального состояния анимации
                animationPlayer.getFrame().save("firstFrame.png", ImageFormat.Png);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            animationPlayer.setTimePosition(animationPlayer.getDuration()); // конечное состояние анимации
            try {
                // последний кадр анимации
                animationPlayer.getFrame().save("lastFrame.png", ImageFormat.Png);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    } finally {
        if (animationsGenerator != null) animationsGenerator.dispose();
    }
} finally {
    if (presentation != null) presentation.dispose();
}

Чтобы все анимации в презентации воспроизводились одновременно, используется класс PresentationPlayer. Этот класс принимает экземпляр PresentationAnimationsGenerator и FPS для эффектов в конструкторе, а затем вызывает событие FrameTick для всех анимаций, чтобы они воспроизводились:

Presentation presentation = new Presentation("animated.pptx");
try {
    PresentationAnimationsGenerator animationsGenerator = new PresentationAnimationsGenerator(presentation);
    try {
        PresentationPlayer player = new PresentationPlayer(animationsGenerator, 33);
        try {
            player.setFrameTick((sender, arguments) ->
            {
                try {
                    arguments.getFrame().save("frame_" + sender.getFrameIndex() + ".png", ImageFormat.Png);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            animationsGenerator.run(presentation.getSlides());
        } finally {
            if (player != null) player.dispose();
        }
    } finally {
        if (animationsGenerator != null) animationsGenerator.dispose();
    }
} finally {
    if (presentation != null) presentation.dispose();
}

Затем сгенерированные кадры можно собрать в видео. Смотрите раздел Convert PowerPoint to Video.

Поддерживаемые анимации и эффекты

Entrance:

Тип анимации Aspose.Slides PowerPoint
Appear not supported supported
Fade supported supported
Fly In supported supported
Float In supported supported
Split supported supported
Wipe supported supported
Shape supported supported
Wheel supported supported
Random Bars supported supported
Grow & Turn not supported supported
Zoom supported supported
Swivel supported supported
Bounce supported supported

Emphasis:

Тип анимации Aspose.Slides PowerPoint
Pulse not supported supported
Color Pulse not supported supported
Teeter supported supported
Spin supported supported
Grow/Shrink not supported supported
Desaturate not supported supported
Darken not supported supported
Lighten not supported supported
Transparency not supported supported
Object Color not supported supported
Complementary Color not supported supported
Line Color not supported supported
Fill Color not supported supported

Exit:

Тип анимации Aspose.Slides PowerPoint
Disappear not supported supported
Fade supported supported
Fly Out supported supported
Float Out supported supported
Split supported supported
Wipe supported supported
Shape supported supported
Random Bars supported supported
Shrink & Turn not supported supported
Zoom supported supported
Swivel supported supported
Bounce supported supported

Motion Paths:

Тип анимации Aspose.Slides PowerPoint
Lines supported supported
Arcs supported supported
Turns supported supported
Shapes supported supported
Loops supported supported
Custom Path supported supported

FAQ

Можно ли конвертировать презентации, защищённые паролем?

Да, Aspose.Slides позволяет работать с password‑protected presentations. При обработке таких файлов необходимо предоставить правильный пароль, чтобы библиотека могла получить доступ к содержимому презентации.

Поддерживает ли Aspose.Slides использование в облачных решениях?

Да, Aspose.Slides может быть интегрирован в облачные приложения и сервисы. Библиотека разработана для работы в серверных окружениях, обеспечивая высокую производительность и масштабируемость при пакетной обработке файлов.

Существуют ли ограничения по размеру презентаций при конвертации?

Aspose.Slides способен обрабатывать презентации практически любого размера. Однако при работе с очень большими файлами могут потребоваться дополнительные системные ресурсы, и иногда рекомендуется оптимизировать презентацию для улучшения производительности.