Variable in file-audio.html.twig I created the following preprocess function to add a value.

function mytheme_preprocess_node__audio(&amp;$variables) {
  $node = $variables['node'];
  $media_field = $node-&gt;get('field_image')-&gt;entity-&gt;uri-&gt;value;
  $variables['poster'] = file_create_url($media_field);
}


I want to output the content of $variables['poster'] in the file-audio.html.twig template. 

&lt;audio {{ attributes }} poster="{{ poster }}"&gt;
  {% for file in files %}
    &lt;source {{ file.source_attributes }} /&gt;
  {% endfor %}
&lt;/audio&gt;


{{ poster }} outputs an empty string. I have tried multiple methods, with no success.

I can get the variable in the field template (field--field-audio.html.twig), but it is not available to the child file template I am using.

How do I get the value of $variables['poster'] in the template file I am using?
So I figured this out, it was not straightforward or obvious, and I could find no forum or post detailing this method, so hopefully it helps others.
The preprocess function changes to preprocess field as: 

function MYTHEME_preprocess_field(array &$variables, $hook) {
  $element = $variables['element'];

  switch ($element['#field_name']) {
    // Machine name of the field
    case 'field_audio':
      $node = \Drupal::request()->attributes->get('node');
      // separate field (machine name = field_image) that holds image for poster
      $media_field = $node->get('field_image')->entity->uri->value; 
      $variables['poster'] = file_create_url($media_field);
      break;
  }
}

Then in the field twig file (field--field-audio.html.twig), replace the appropriate item.content section (or all of them as I did, just in case!)


      {% set attr = item.content['#attributes']|merge({'poster': poster}) %}
      {% set mycontent = item.content|merge({'#attributes': attr}) %}

      &lt;div{{ attributes.addClass(classes, 'field--item') }}&gt; {{ mycontent }} &lt;/div&gt;


Finally in the file-audio.html.twig template you just need to add the poster="{{poster}}" like:

&lt;audio {{ attributes }} style="background: transparent url({{ attributes.poster }});"&gt;

I've done the same for Video, i.e. using a separate field for the poster of the html5 video tag, using the same method EXCEPT in the field template #attributes is #player_attributes as you should be able to see in the file twig template, named video-player-formatter.html.twig in my case. Happy to post the code if anyone needs it.

Thanks to the drupal forums, twig documentation and of course stackexchange for the snippets I picked up along the way to figure this out.