钛合金启动和停止声音

时间:2013-04-15 01:10:06

标签: javascript titanium titanium-mobile

我在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部分的来源。我很确定我的错误就在那里。

1 个答案:

答案 0 :(得分: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();
});