动态src ------ js >>>转换为html

时间:2019-03-09 19:57:13

标签: javascript html

我有一个可以从此路径播放的音频文件。

/posts/THEFORCE.WAV

       <audio controls="controls" id="audio_player">
          <source src="/posts/THEFORCE.WAV" type="audio/ogg" />
          <source src="/posts/THEFORCE.WAV" type="audio/mpeg" />
        </audio>

我可以接受用户的输入 并通过index.js保存到服务器的路径

const {song} = req.files

song: `/posts/${song.name}`

Output =  song: '/posts/THEFORCE.WAV' //This is not code just showing that song is a string

问题是...

如何使html src“ path”动态化为js const歌曲

2 个答案:

答案 0 :(得分:0)

您可以选择源元素并将其src值替换为您的歌曲

const song = '/posts/NEW.wav'; // replace this with your dynamic fetched song
const sourceElems = document.querySelectorAll('#audio_player > source');

[...sourceElems].forEach(source => {
  source.src = song
  console.log('replaced source src:', source.src);
});
<audio controls="controls" id="audio_player">
    <source src="/posts/THEFORCE.WAV" type="audio/ogg" />
    <source src="/posts/THEFORCE.WAV" type="audio/mpeg" />
</audio>

答案 1 :(得分:0)

const post = mongoose.model('UploadSchema',UploadSchema)

   <audio controls="controls" id="audio_player">
      <source src="{{post.song}}" type="audio/ogg" />
      <source src="{{post.song}}" type="audio/mpeg" />
    </audio>