Convertir presentaciones de PowerPoint a video en Android

Al convertir su presentación de PowerPoint a video, obtiene

  • Aumento de accesibilidad: Todos los dispositivos (independientemente de la plataforma) vienen equipados con reproductores de video por defecto, a diferencia de las aplicaciones de apertura de presentaciones, por lo que los usuarios encuentran más fácil abrir o reproducir videos.
  • Mayor alcance: A través de videos, puede llegar a una gran audiencia y ofrecerles información que de otro modo podría resultar tediosa en una presentación. La mayoría de encuestas y estadísticas sugieren que la gente ve y consume videos más que otros formatos de contenido, y generalmente prefieren este tipo de contenido.

Conversión de PowerPoint a video en Aspose.Slides

Aspose.Slides admite la conversión de presentaciones a video.

  • Utilice Aspose.Slides para generar un conjunto de fotogramas (a partir de las diapositivas de la presentación) que correspondan a una determinada FPS (cuadros por segundo)
  • Utilice una utilidad de terceros como ffmpeg (for java) para crear un video a partir de los fotogramas.

Convertir PowerPoint a video

  1. Añada esto a su archivo POM:
   <dependency>
     <groupId>net.bramp.ffmpeg</groupId>
     <artifactId>ffmpeg</artifactId>
     <version>0.7.0</version>
   </dependency>
  1. Descargue ffmpeg aquí.

  2. Ejecute el código Java de PowerPoint a video.

Este código Java le muestra cómo convertir una presentación (que contiene una figura y dos efectos de animación) a un video:

Presentation presentation = new Presentation();
try {
    // Añade una forma de sonrisa y luego la anima
    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();
    }

    // Configura la carpeta de binarios de ffmpeg. Ver esta página: 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();
}

Efectos de video

Puede aplicar animaciones a objetos en las diapositivas y usar transiciones entre ellas.

Las animaciones y transiciones hacen que las presentaciones sean más atractivas e interesantes, y lo mismo ocurre con los videos. Añadamos otra diapositiva y transición al código de la presentación anterior:

// Añade una forma de sonrisa y la anima

// ...

// Añade una nueva diapositiva y transición animada

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 también admite animación de textos. Así que animamos párrafos en objetos, que aparecerán uno tras otro (con el retraso configurado a un segundo):

Presentation presentation = new Presentation();
try {
    // Añade texto y animaciones
    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();
    }

    // Configura la carpeta de binarios de ffmpeg. Ver esta página: 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();
}

Clases de conversión de video

Para permitirle realizar tareas de conversión de PowerPoint a video, Aspose.Slides proporciona las clases PresentationAnimationsGenerator y PresentationPlayer.

PresentationAnimationsGenerator le permite establecer el tamaño del fotograma para el video (que se creará más adelante) a través de su constructor. Si pasa una instancia de la presentación, se utilizará Presentation.SlideSize y generará animaciones que PresentationPlayer utiliza.

Cuando se generan las animaciones, se genera un evento NewAnimation para cada animación sucesiva, que tiene el parámetro IPresentationAnimationPlayer. Este último es una clase que representa un reproductor para una animación independiente.

Para trabajar con IPresentationAnimationPlayer, se utilizan la propiedad Duration (la duración total de la animación) y el método SetTimePosition. Cada posición de animación se establece dentro del rango 0 a duración, y luego el método GetFrame devolverá un BufferedImage que corresponde al estado de la animación en ese momento:

Presentation presentation = new Presentation();
try {
    // Añade una forma de sonrisa y la anima
    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); // estado inicial de la animación
            try {
                // mapa de bits del estado inicial de la animación
                animationPlayer.getFrame().save("firstFrame.png", ImageFormat.Png);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            animationPlayer.setTimePosition(animationPlayer.getDuration()); // estado final de la animación
            try {
                // último fotograma de la animación
                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();
}

Para que todas las animaciones de una presentación se reproduzcan simultáneamente, se utiliza la clase PresentationPlayer. Esta clase toma una instancia de PresentationAnimationsGenerator y FPS para los efectos en su constructor y luego llama al evento FrameTick para todas las animaciones y así reproducirlas:

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();
}

Luego los fotogramas generados pueden compilarse para producir un video. Consulte la sección Convertir PowerPoint a video.

Animaciones y efectos compatibles

Entrada:

Tipo de animación Aspose.Slides PowerPoint
Appear no compatible compatible
Fade compatible compatible
Fly In compatible compatible
Float In compatible compatible
Split compatible compatible
Wipe compatible compatible
Shape compatible compatible
Wheel compatible compatible
Random Bars compatible compatible
Grow & Turn no compatible compatible
Zoom compatible compatible
Swivel compatible compatible
Bounce compatible compatible

Énfasis:

Tipo de animación Aspose.Slides PowerPoint
Pulse no compatible compatible
Color Pulse no compatible compatible
Teeter compatible compatible
Spin compatible compatible
Grow/Shrink no compatible compatible
Desaturate no compatible compatible
Darken no compatible compatible
Lighten no compatible compatible
Transparency no compatible compatible
Object Color no compatible compatible
Complementary Color no compatible compatible
Line Color no compatible compatible
Fill Color no compatible compatible

Salida:

Tipo de animación Aspose.Slides PowerPoint
Disappear no compatible compatible
Fade compatible compatible
Fly Out compatible compatible
Float Out compatible compatible
Split compatible compatible
Wipe compatible compatible
Shape compatible compatible
Random Bars compatible compatible
Shrink & Turn no compatible compatible
Zoom compatible compatible
Swivel compatible compatible
Bounce compatible compatible

Rutas de movimiento:

Tipo de animación Aspose.Slides PowerPoint
Lines compatible compatible
Arcs compatible compatible
Turns compatible compatible
Shapes compatible compatible
Loops compatible compatible
Custom Path compatible compatible

Preguntas frecuentes

¿Es posible convertir presentaciones protegidas con contraseña?

Sí, Aspose.Slides permite trabajar con presentaciones protegidas con contraseña. Al procesar dichos archivos, debe proporcionar la contraseña correcta para que la biblioteca pueda acceder al contenido de la presentación.

¿Aspose.Slides admite su uso en soluciones en la nube?

Sí, Aspose.Slides puede integrarse en aplicaciones y servicios en la nube. La biblioteca está diseñada para funcionar en entornos de servidor, garantizando alto rendimiento y escalabilidad para el procesamiento por lotes de archivos.

¿Existen limitaciones de tamaño para las presentaciones durante la conversión?

Aspose.Slides es capaz de manejar presentaciones de prácticamente cualquier tamaño. Sin embargo, al trabajar con archivos muy grandes, pueden requerirse recursos del sistema adicionales, y a veces se recomienda optimizar la presentación para mejorar el rendimiento.