Error when use media_player.play_media with if clause in media_content_id

Hi all
My automation cast media file to Google Cast speaker
If I use

service: media_player.play_media
data:
  entity_id: media_player.phong_khach
  media_content_id: media-source://media_source/local/mycontrol/voice01.mp3
  media_content_type: music

or

service: media_player.play_media
data:
  entity_id: media_player.phong_khach
  media_content_id: media-source://media_source/local/mycontrol/voice02.mp3
  media_content_type: music

it runs successfully, it can play media file to Google Cast

but if I use IF Clause

service: media_player.play_media
data:
  entity_id: media_player.phong_khach
  media_content_id: >-
    {% if is_state('binary_sensor.myswitch', 'on')
    %}media-source://media_source/local/mycontrol/voice01.mp3{% else
    %}media-source://media_source/local/mycontrol/voice02.mp3{% endif
    %}
  media_content_type: music

then it can not play media file and there is error

Logger: homeassistant.components.cast.media_player
Source: components/cast/media_player.py:316
Integration: Google Cast (documentation, issues)
First occurred: 7:00:29 PM (5 occurrences)
Last logged: 10:13:56 PM

Failed to cast media http://192.168.1.22:8123/media/local/mycontrol/voice01.mp3?authSig=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI0ZmNkYWFmNjQ3YjE0NzMzODZkY2U1MzM5YzM4ZGYxYyIsInBhdGgiOiIvbWVkaWEvbG9jYWwvbXljb250cm9sL3RhdF9ub25nbGFuaC5tcDMiLCJpYXQiOjE2MjU5MzAwMzYsImV4cCI6MTYyNjAxNjQzNn0.cqcrNfBih3quE3YlsdzDaimqicAS1o_Ld4fXpbn3VWY from internal_url (http://192.168.1.22:8123). Please make sure the URL is: Reachable from the cast device and either a publicly resolvable hostname or an IP address

but I paste this to my browser, I can get media file

http://192.168.1.22:8123/media/local/mycontrol/voice01.mp3?authSig=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI0ZmNkYWFmNjQ3YjE0NzMzODZkY2U1MzM5YzM4ZGYxYyIsInBhdGgiOiIvbWVkaWEvbG9jYWwvbXljb250cm9sL3RhdF9ub25nbGFuaC5tcDMiLCJpYXQiOjE2MjU5MzAwMzYsImV4cCI6MTYyNjAxNjQzNn0.cqcrNfBih3quE3YlsdzDaimqicAS1o_Ld4fXpbn3VWY

Please help me. Thanks

As you can see, the media source is properly resolved to an http link, so the “if” is unlikely to be the culprit.

So how is yaml code in that case ?
I want to play voice01.mp3 if states of myswitch is on
and play voice02.mp3 if states of myswitch is off

Thanks

Humour me. Try it like this:

  media_content_id: >
    {% if is_state('binary_sensor.myswitch', 'on') %}
      media-source://media_source/local/mycontrol/voice01.mp3
    {% else %}
      media-source://media_source/local/mycontrol/voice02.mp3
    {% endif %}

I don’t expect it will help, but that formatting hurts my brain.

Yes, it can work now.
Your code has better format and a little bit difference

media_content_id: >

and

media_content_id: >-

character “-”

Thanks so much