i record sound in c#(wpf) , when data sound card available calls event:
void mywavein_dataavailable(object sender, waveineventargs e) { (int index = 0; index < e.bytesrecorded; index += 2)//here convert in loop stream floating number samples { short sample = (short)((e.buffer[index + 1] << 8) | e.buffer[index + 0]); samples32queue.enqueue(sample/32768f); } //***do processing data inside queue } as can see push every sample recorded buffer queue declared that:
queue<float> samples32queue = new queue<float>(); as can see inside event after for loop want processing on queue. worry while processing data, new samples come sound card , processing got lost.
- what right approach make that?
- is processing call event static method/non-static?
given fact can buffer samples , process them later, consider using blockingcollection. blockingcollection excellent solution producer-consumer pattern, understanding, case. on 1 side have mywavein_dataavailable() method producer adding samples collection, , on other end have consuming thread (it doesn't have thread, though) collecting samples , processing them. there various ways consumer can implemented, , documented in msdn.
edit: see following example, did not test should give start point:
class producerconsumerexample { blockingcollection<float> samples32collection; thread consumer; public producerconsumerexample() { samples32collection = new blockingcollection<float>(); consumer = new thread(() => launchconsumer()); consumer.start(); //you don't have luanch consumer here... } void terminate() //call terminate consumer { consumer.abort(); } void mywavein_dataavailable(object sender, waveineventargs e) { (int index = 0; index < e.bytesrecorded; index += 2)//here convert in loop stream floating number samples { short sample = (short)((e.buffer[index + 1] << 8) | e.buffer[index + 0]); samples32collection.add(sample / 32768f); } } void launchconsumer() { while (true /* insert abort condition here*/) { try { var sample = samples32collection.take(); //this thread wait here until producer add new item(s) collection process(sample); //in meanwhile, more samples added collection //but not processed until thread done process(sample) } catch (invalidoperationexception) { } } } }
Comments
Post a Comment