javascript - angularJS通过$http获取的src值,然后在页面中添加<audio>标签以后,为什么获取不到它的属性呀?
大家讲道理
大家讲道理 2017-04-11 09:50:45
[JavaScript讨论组]

使用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);这两行执行的结果

求解,各位大神

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(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)
})
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号