@hyext-beyond/hy-ui-native
Version:
A native lib polyfill for huya miniapp
117 lines (116 loc) • 3.09 kB
JavaScript
function once(cb) {
var flag = false;
return function () {
if (flag) return;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
cb.apply(this, args);
flag = true;
};
}
function initEvent(vm, cb) {
vm.audio.oncanplay = once(function () {
cb(null);
});
vm.audio.onerror = once(function (e) {
cb(e);
});
vm.audio.onended = function () {
vm._processLoop();
vm.onEnd && vm.onEnd(true);
};
}
function initElm(vm, src) {
vm.audio = document.createElement('audio');
vm.audio.control = false;
vm.audio.src = src;
document.body.appendChild(vm.audio);
}
function removeElm(vm) {
if (vm.audio) {
document.body.removeChild(vm.audio);
vm.audio = null;
}
}
// 音源地址
// 初始化成功回调
var Sound = /*#__PURE__*/function () {
function Sound(src, canPlayCb) {
var _this = this;
this.loopCount = 0;
this.onEnd = void 0;
this.play = function (cb, onError) {
_this.onEnd = cb;
var promise = _this.audio.play();
if (promise !== undefined) {
promise.then(function (_) {
// Autoplay started!
})["catch"](function (error) {
onError && onError(error);
});
}
};
this.pause = function () {
_this.audio.pause();
};
this.stop = function (cb) {
_this.audio.pause();
_this.audio.currentTime = 0;
cb();
};
this.release = function () {
_this.pause();
setTimeout(function () {
removeElm(_this);
});
};
initElm(this, src);
initEvent(this, canPlayCb);
}
var _proto = Sound.prototype;
_proto._processLoop = function _processLoop() {
var loopCount = this.loopCount;
loopCount = --loopCount;
if (loopCount > 0) {
this.audio.currentTime = 0;
this.audio.play();
this.loopCount = loopCount;
}
};
_proto.setVolume = function setVolume(v) {
if (isNaN(v)) throw new TypeError('args[0] must be a number');
this.audio.volume = v;
};
_proto.setPan = function setPan() {
console.warn('web暂时不支持setPan方法');
};
_proto.setCategory = function setCategory() {
console.warn('web暂时不支持setCategory方法');
};
_proto.setNumberOfLoops = function setNumberOfLoops(v) {
if (isNaN(v)) throw new TypeError('args[0] must be a number');
this.loopCount = v;
};
_proto.setCurrentTime = function setCurrentTime(v) {
if (isNaN(v)) throw new TypeError('args[0] must be a number');
this.audio.currentTime = v;
};
_proto.getVolume = function getVolume() {
return this.audio.volume;
};
_proto.getPan = function getPan() {
console.warn('web暂时不支持getPan方法');
};
_proto.getNumberOfLoops = function getNumberOfLoops() {
return this.loopCount;
};
_proto.getCurrentTime = function getCurrentTime(cb) {
cb(this.audio.currentTime);
};
return Sound;
}();
export var createSound = function createSound(src, cb) {
return new Sound(src, cb);
};
export default createSound;