1

我有这个在 Javascript 中工作,但似乎无法让它在 Titanium 上工作。

这是代码:

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 部分出现的地方。我很确定我的错误在那里。

4

1 回答 1

1

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

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();
});
于 2013-04-15T03:02:21.307 回答