angularJS通过$http获取的src值,然后在页面中添加<audio>标签以后,为什么获取不到它的属性呀?

新手上路,请多包涵

使用angular+ionic做一个音乐播放器的时候,通过$http获取到音乐的属性(name,title,introduce,src),然后通过DOM生成audio标签并且添加src,
在页面中通过JS可以获取到<audio>的DOM元素,但是无法获取<audio>的.duration属性以及其他的属性。请问下这是什么情况呀?
部分代码:

   function createAudio(src) {
            var AudioPlayer = document.createElement('audio');
            AudioPlayer.setAttribute('src', src);
            AudioPlayer.setAttribute('autoplay', true);
            AudioPlayer.setAttribute('controls', true);
            AudioPlayer.id = 'musicPlayer';
            document.body.appendChild(AudioPlayer);

        }
playList是获取到的数据对象数组,将数组中第一个对象添加到audio中,

                       /*PLAY MUSIC*/
        $scope.addMusic = function (music_id) {
            MainService.getmusicinfo(music_id, function (res) {
                if (!res)return;
                localStorage.setItem('play', JSON.stringify(playList));
                $rootScope.playList = JSON.parse(localStorage.getItem('play') || '');
                if(!document.getElementById('musicPlayer')){
                    createAudio($rootScope.playList[0].file);
                    var musicPlayer = document.getElementById('musicPlayer');
                    console.log(musicPlayer);
                    console.log(musicPlayer.duration);
                }else{
                    document.body.removeChild(document.getElementById('musicPlayer'));
                    var musicPlayer = document.getElementById('musicPlayer');
                    createAudio($rootScope.playList[0].file);
                }
            })
        }

console.log(musicPlayer);
console.log(musicPlayer.duration);这两行执行的结果

clipboard.png

求解,各位大神

阅读 4.5k
2 个回答
新手上路,请多包涵

我也正考虑这个问题 不知道你解决没

A double. If the media data is available but the length is unknown, this value is NaN. If the media is streamed and has no predefined length, the value is Inf.
https://developer.mozilla.org...

你这要在音频文件加载完成后再获取duration.

https://developer.mozilla.org...

audio.addEventListener('canplay', function(e){
  console.log(audio.duration)
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题