You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决R语言Shiny中gganimate生成的.mp4动画无法显示问题

问题根因

  1. 前端组件类型不匹配:你用imageOutput()组件加载mp4视频,浏览器会把视频资源当成图片解析,自然无法正常渲染,只会显示缺失图标。
  2. 临时文件路径不匹配:代码里用tempfile()生成了临时路径,但是anim_save()却硬写了固定文件名outfile.mp4,返回src的时候也用了固定文件名,路径不一致也会导致资源加载失败。

修正后的完整代码

library(shiny)
library(gapminder)
library(ggplot2)
library(gganimate)
library(av) # 确保已经安装av包用于渲染mp4

p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
  geom_point() +
  geom_smooth(aes(group = year), 
              method = "lm", 
              show.legend = FALSE) +
  facet_wrap(~continent, scales = "free") +
  scale_x_log10() +
  transition_manual(year)

ui <- shinyUI(basicPage(
    imageOutput("gif"), ## 正常保留
    uiOutput("mp4")  ## 替换为uiOutput输出原生video标签
))

server <- shinyServer(function(input, output) {

  output$gif <- renderImage({
    outfile <- tempfile(fileext='.gif')
    anim_gif <- animate(p)
    anim_save(outfile, anim_gif)
    # 返回资源列表
    list(src = outfile,
         contentType = 'image/gif'
    )}, deleteFile = TRUE)
  
  output$mp4 <- renderUI({
    outfile <- tempfile(fileext='.mp4')
    anim_mp4 <- animate(p, renderer = av_renderer())
    anim_save(outfile, anim_mp4)
    # 直接返回HTML5 video标签
    tags$video(
      src = outfile,
      type = "video/mp4",
      controls = NA, # 显示播放控制条
      width = "800px"
    )
  })
  
})

shinyApp(ui = ui, server = server)

注意事项

  • 运行前请执行install.packages("av")确保渲染依赖正常
  • 若需要自动播放可以给video标签添加autoplay = NA、loop = NA属性
  • shiny会自动处理tempfile生成的临时资源,不需要额外配置删除逻辑

内容的提问来源于stack exchange,提问作者R_Pseudo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 10:36:00