1

我想创建一个随机声音音序器,只是为了了解更多关于 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

4

1 回答 1

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();
 }
于 2012-10-28T13:38:54.263 回答