使用HTML5音频元素使用AngularJS创建新指令

时间:2014-11-24 12:09:39

标签: javascript html5 angularjs audio

我是角度新手,我使用angular指令创建了音频按钮:

app.directive('soundButton', [function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            var audioSrc = attrs.origem;
            var audio = new Audio(audioSrc);

            scope.play = function () {
                if (audio.paused) {
                    audio.play();
                } else {
                    audio.pause();
                }
            };

            element.css({
                borderRadius: '50%',
                width: '100px',
                height: '100px', 
                backgroundColor: 'red',
                display: 'inline-block'
            });

        }
    }
}]);

...并将html代码放在我的页面上:

<section id="bla" data-ng-controller="Ctrl">
            <sound-button data-ng-click="play()" origem="http://sampleswap.org/samples-ghost/DRUMS%20(FULL%20KITS)/sys100%20drumkit/24[kb]909-klick.aif.mp3" class="col-md-4"></sound-button>
            <sound-button data-ng-click="play()" origem="http://sampleswap.org/samples-ghost/DRUMS%20(FULL%20KITS)/sys100%20drumkit/2[kb]hihat_closed.aif.mp3" class="col-md-4"></sound-button>
            <sound-button data-ng-click="play()" origem="http://sampleswap.org/samples-ghost/DRUMS%20(FULL%20KITS)/sys100%20drumkit/34[kb]noicybell.aif.mp3" class="col-md-4"></sound-button>
        </section>

但是我总是点击音频按钮,它会播放相同的声音。 (我怀疑这可能是一系列元素问题)

FIDDLERJS http://jsfiddle.net/qumjmz9y/

2 个答案:

答案 0 :(得分:3)

音频元素有源元素。所以你必须改变这个元素。看here

答案 1 :(得分:1)

您应该定义内部SOURCE标记

app.directive('soundButton', [function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            var audioSrc = attrs.origem,
                audio = angular.element('<audio/>'),
                inner = angular.element('<source/>');

            inner.attr('src', audioSrc);
            audio.attr('autoplay', true);
            audio.attr('control', false);
            //audio.attr('loop', true);
            element.append(audio);
            audio.append(inner);

            scope.play = function () {

                if (audio[0].paused) {
                    audio[0].play();
                } else {
                    audio[0].pause();
                }
            };

            element.css({
                borderRadius: '50%',
                width: '100px',
                height: '100px', 
                backgroundColor: 'red',
                display: 'inline-block'
            });

        }
    }
}]);