钛开始和停止声音

问题描述:

我有这个工作在Javascript中,但似乎无法让它在钛上工作。钛开始和停止声音

下面是代码:

var index = 0; 
var i = 0; 

// Filename 
var wordSoundArray = []; 

wordSoundArray.push('audio/the.mp3'); 
wordSoundArray.push('audio/of.mp3'); 
wordSoundArray.push('audio/and.mp3'); 
wordSoundArray.push('audio/a.mp3'); 
wordSoundArray.push('audio/to.mp3'); 
wordSoundArray.push('audio/in.mp3'); 
wordSoundArray.push('audio/is.mp3'); 
wordSoundArray.push('audio/you.mp3'); 
wordSoundArray.push('audio/that.mp3'); 
wordSoundArray.push('audio/it.mp3'); 
wordSoundArray.push('audio/he.mp3'); 
wordSoundArray.push('audio/was.mp3'); 
wordSoundArray.push('audio/for.mp3'); 
wordSoundArray.push('audio/on.mp3'); 
wordSoundArray.push('audio/are.mp3'); 

newWordBtn.addEventListener("click", function(e){ 
    wordLabel.text = newWordArray[i++]; 
    if (i === newWordArray.length) 
      i = 0; 

    var snd = Titanium.Media.createSound({url:wordSoundArray[index++]}); 
    if (index === wordSoundArray.length) 
      index = 0; 
    if (snd.isPlaying()) { 
     snd.stop(); 
     snd.play(); 
    } else { 
     snd.play(); 
    } 


}); 

当用户按下他们得到了一个新词,并以该字而来的声音的按钮。但是,如果用户在声音结束之前按下按钮,则只是开始新声音并且它们彼此重叠。这就是代码的snd.isPlaying部分来的地方。我很确定我的错误在那里。

+0

代码似乎不完整的,变量'i'从哪里来?这是在一个循环? –

+0

我更新了代码以包含变量语句和我遇到问题的数组。 –

所以你确实有死代码在这里:

var snd = Titanium.Media.createSound({url:wordSoundArray[index++]})); 
... 
// You just created the sound, so it will never be playing right off the bat 
if (snd.isPlaying()) { 
    // This will never be called 
    snd.stop(); 
    snd.play(); 
} else { 
    // This will happen every time the user clicks the button 
    snd.play(); 
} 

我认为它很好的做法,预加载你的所有的声音的资产开始执行之前,所以也许尝试用表格的条目替换您wordSoundArray

wordSoundArray.push(Titanium.Media.createSound({url:'audio/the.mp3'}); 

一旦你做到了这一点(我们所有的声音资产预装,这将有利于记忆太),我们可以监听改变这样的事情:

在你的代码
newWordBtn.addEventListener("click", function(e){ 
    wordLabel.text = newWordArray[i++]; 
    if (i === newWordArray.length) 
      i = 0; 

    // Instead of creating the sound, just fetch it! 
    var snd = wordSoundArray[index++]; 

    if (index === wordSoundArray.length) 
      index = 0; 
    // Now this will work, but maybe you want to make sure all the sounds are off instead? 
    if (snd.isPlaying()) { 
     snd.stop(); 
     snd.play(); 
    } else { 
     snd.play(); 
    } 
}); 

展望虽然,它似乎要停止以前的声音播放,然后开始下一个,所以你需要改变监听到这一点:

newWordBtn.addEventListener("click", function(e){ 
    wordLabel.text = newWordArray[i++]; 
    if (i === newWordArray.length) 
      i = 0; 
    // Stop the last sound from playing 
    if(index > 0) { 
      var lastSound = wordSoundArray[index-1]; 
      lastSound.stop(); 
    } 

    // Instead of creating the sound, just fetch it! 
    var nextSound = wordSoundArray[index++]; 

    if (index === wordSoundArray.length) 
      index = 0; 
    // Play the next sound 
    nextSound.play(); 
}); 
+0

谢谢,谢谢,谢谢!我一整天都在努力。我搜索了一切,但只有一些帮助在这里和那里。虽然学到了更多。 :) –