我在页面上有一堆声音,类似于声音网格示例。其中一些曲目是音乐曲目,我想以不同的方式对待它们。大多数声音可以互相播放,这就是意图,但是,没有音乐曲目应该能够播放另一首音乐曲目。认为单选按钮。SoundJS音乐剪辑应该互相切换开关
我有一些非常模糊的代码,用于检测单击时是否播放其他轨道并停止轨道,并切换轨道的css(播放图标等)。但现在,添加第3或第4首曲目的混音变得不羁。
声音被加载并存储在可重复使用的声音情况下,看上去就像一个哈希:
mySounds["sound1"]= createjs.Sound.createInstance("sound1");
...
当HTML按钮被点击(我不是目前使用的数据类型的属性,是从较早的尝试,但我想这可能是有用的):
<button type="button" class="btn btn-vol btn-sm" data-type="music" data-track="music1" onclick="play(this)">
<span class="glyphicon glyphicon-play bplay"></span></button>
我目前做的:
function play(target) {
//define some stuff from html
musicTrack = $(target).attr('data-track');
music1 = $('button[data-track="music1"]');
music2 = $('button[data-track="music2"]');
myInstance = mySounds[id] //id is defined elsewhere
toggle = $(target).find('span.bplay'); //this is where I have the play/pause icons
//For all cases, not just music I find the play icon and swap it.
if(toggle.hasClass('glyphicon-play')){ //the sound is ready to play. if it had a stop icon it would mean it was already playing
toggle.removeClass('glyphicon-play');
toggle.addClass('glyphicon-stop')
//special case for music Tracks
if(musicTrack == "music1") { //If I clicked on music track 1
if(mySounds[musicTrack2].position !=0){ //if it isn't 0, it's playing!
music2.find('span.bplay).removeClass('glyphicon-stop');
music2.find('span.bplay').addClass('glyphicon-play');
mySounds[musicTrack2].stop();
}
else {
//do nothing because track 2 isn't playing
}
} else if (musicTrack=="music2"){ //If I clicked on music track 2
if(mySounds[musicTrack2].position !=0){
music1.find('span.bplay').removeClass('glyphicon-stop');
music1.find('span.bplay').addClass('glyphicon-play');
mySounds[musicTrack1].stop();
}
else {
//do nothing because track 1 isn't playing
}
myInstance.play(); // play the clicked on instance
}
else {
//if the glyphicon does not say play (says stop) then we stop the sound etc..
toggle.removeClass('glyphicon-stop');
toggle.addClass('glyphicon-play');
myInstance.stop();
}
}
我没有检查上面的语法,因为我从我的代码手中复制它,只保留相关的位,但所有这些工作。我点击music1,如果音乐2没有播放 - 它播放。如果音乐2正在播放,则停止播放音乐2,将其停止图标播放并播放音乐1.我的实际代码会在停止之前对声音进行一些补间,以便它们交叉淡入淡出。
我不是程序员,但我希望能够以更高效/优雅的方式做到这一点。当然有一种方法!
只是为了澄清,问题是“这个问题是否有更高效/优雅的解决方案?” – OJay
基本上,如果我只想要2个声音互相切换,就像这里显示的那样,我可以用这个不雅的代码来处理 - 但是我想要4或5个声音,每一个都可以切换图形(按钮)和回放以及方式我已经设置它会变得非常难看和困惑。所以,是的。 – dijon