【发布时间】:2015-09-19 19:28:41
【问题描述】:
我正在构建一个应用程序,允许用户设置工作持续时间 (workSecs),完成后会发出声音提醒用户 (buzzer.mp3),然后由用户设置的休息持续时间 (breakSecs) 开始,并且当休息完成时,声音会提醒用户(timer.mp3)。我正在使用 switch 语句来测试 workSecs === 0 和 breakSecs === 0 的时间,并且当任一条件为真时,独特的警报都会消失。
我的时钟有一个 setInterval 函数,奇怪的是,当我将 switch 语句放在 setInterval 中时,声音可以工作,但它是重复的,因为它在 setInterval 函数中,但是当我从 setInterval 函数中删除它时,警报不起作用当 switch 语句中的条件为真时。
我不确定这是否是范围问题,因为 chrome 的开发人员或 firebug 中没有错误。
//audiotype object declare and sound method property
var Audiotypes = {
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav",
soundbits: function (sound) {
var audio_element = document.createElement('audio')
if (audio_element.canPlayType) {
for (var i = 0; i < arguments.length; i++) {
var source_element = document.createElement('source')
source_element.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i)) source_element.setAttribute('type', Audiotypes[RegExp.$1])
audio_element.appendChild(source_element)
}
audio_element.load()
audio_element.playclip = function () {
audio_element.pause()
audio_element.currentTime = 0
audio_element.play()
}
return audio_element
}
}
}
// Clock object declared
var Clock = {
workSeconds: 0,
breakSeconds: 0,
// startTimer function begins here
startTimer: function () {
var self = this,
workSecs = this.workSeconds + 1,
breakSecs = this.breakSeconds + 1;
//workSecs and breakSecs switch statement begins here
switch (true) {
case (workSecs === 0):
alert('workSecs now 0')
var buzz = Audiotypes.soundbits('sounds/buzzer.mp3');
buzz.play();
break;
case (breakSecs === 0):
alert('breakSecs now 0')
var timer = Audiotypes.soundbits('sounds/timer.mp3');
timer.play();
}
// startTimer interval function begins here
this.interval = setInterval(function () {
if (workSecs > 0) {
workSecs--;
mins.html(Math.floor(workSecs / 60 % 60));
secs.html(parseInt(workSecs % 60));
} else if (breakSecs > 0) {
breakSecs--;
mins.html(Math.floor(breakSecs / 60 % 60));
secs.html(parseInt(breakSecs % 60));
} else if (breakSecs === 0) {
workSecs = self.workSeconds + 1;
breakSecs = self.breakSeconds + 1;
}
self.workSeconds = workSecs;
if (mins.html().length === 1) {
mins.html('0' + mins.html());
}
if (secs.html().length === 1) {
secs.html('0' + secs.html());
}
}, 1000)
}, //there is more code after this point but it's irrelevant to the problem
【问题讨论】:
-
您尝试播放时是否加载了音频文件?
-
@gre_gor 加载音频文件,但它们只会在 setinterval 函数内播放。
标签: javascript jquery audio switch-statement setinterval