Hello there,
give it try with… (replace page with your p variable)
{# get all the images from the page media #}
{% set images = page.media.images %}
{# create an empty array to hold your bg images #}
{% set bg_images = [] %}
{# loop over all the images and put only 'gif' images into the new array #}
{% for filename, image in images %}
{% if filename ends with 'gif' %]
{% set bg_images = bg_images|merge(image) %}
{% endif %}
{% endfor %}
The example comes from this post. There is some more explanation.
Regards,
Michael