我想创建一个随机声音序列器,只是为了更多地了解WebAudio和Dart。
我的想法是加载一些声音示例并无休止地随机播放。
为此,我已经加载了所有文件,在arraybuffer中解码它们并使用以下函数将它们播放:
void startAudio()
{
int index=random.nextInt(buffers.length);
print("Audio played [${index}].");
source.buffer=buffers[index];
source.connect(context.destination, 0, 0);
source.start(0);
Timer timer=new Timer(100, this.proceed);
}
void proceed(Timer timer)
{
this.startAudio();
}
问题是经过一段时间后,声音停止播放。
出了什么问题?
这是我做我想做的最好的方式吗?
如果有人想测试我的代码,请点击以下链接: http://cg.usr.sh/Dart/WebAudioTest/WebAudioTest.html
答案 0 :(得分:2)
在随机改变事物之后,我按照我的期望让它发挥作用。
import 'dart:html';
import 'dart:math';
import 'dart:async';
class AudioMaker
{
List<String> urls;
AudioContext context;
List<AudioBuffer> buffers;
Random random;
AudioMaker()
{
this.urls=new List<String>();
this.context=new AudioContext();
this.buffers=new List<AudioBuffer>();
this.random=new Random(0);
}
void checkAndStart()
{
if(buffers.length == urls.length)
{
Timer timer=new Timer.repeating(500, this.startAudio);
}
}
void startAudio(Timer timer)
{
int index=random.nextInt(this.buffers.length);
print("Audio played [${index}].");
AudioBufferSourceNode source=context.createBufferSource();
source.buffer=this.buffers[index];
source.connect(context.destination, 0, 0);
source.start(0);
}
void _decodeAudio(url)
{
HttpRequest hr=new HttpRequest.get(url, (req){
this.context.decodeAudioData(req.response, (audio_buff)
{
print("${url} decoded.");
this.buffers.add(audio_buff);
checkAndStart();
}, (evt)
{
print("Error");
});
});
hr.responseType="arraybuffer";
}
void loadAndStart()
{
for(String url in this.urls)
{
this._decodeAudio(url);
}
}
}
main()
{
AudioMaker audioMaker=new AudioMaker();
audioMaker.urls.add("bark.ogg");
audioMaker.urls.add("drip.ogg");
audioMaker.urls.add("glass.ogg");
audioMaker.urls.add("sonar.ogg");
audioMaker.loadAndStart();
}