dynamic size for microphone input - unity3d

i am using unity3d to record some input from the microphone using:
getAudioSource.clip = Microphone.Start(null, true,20, 44100);
The problem is that this records for a standard time period of 20 secs, which i don't want. I would like to record untill a finish a recording by:
Microphone.End(deviceName);
and the resulting clip should have the exact size i recorded, not a standard 20 secs. Right now, if i end the recording after 3 secs, the resulting audio is 20 secs in length. I would like it to have 3 secs.
How can this be done?

the size isn't changeable, it's fixed size.. but i did manage to trim the audio to the actual size.
UPDATE
AudioClip ac = getAudioSource.clip;
float lengthL = ac.length;
float samplesL = ac.samples;
float samplesPerSec = (float)samplesL/lengthL;
float[] samples = new float[(int)(samplesPerSec * timeSinceRecordStarted)];
ac.GetData(samples,0);
getAudioSource.clip = AudioClip.Create("RecordedSound",(int)(timeSinceRecordStarted*samplesPerSec),1,44100,false,false);
getAudioSource.clip.SetData(samples,0);
where timeSinceRecordStarted is the length in secs of the recording and getAudioSource initially holds the microphone audio clip.

Related

STM32 HAL Nucleo F446RE Quadrature Encoder

I have a problem with the quadrature encoder mode on timer TIM3 of my
STM32F446RE /
NUCLEO-F446RE:
TIM3 counts on every rising edge on the first signal.
The CNT register counts up and I read the value with 1 Hz and then
I set the register to 0.
When I look on the
oscilloscope
the frequency is half as high as the value from the
CNT register output (1hz).
Why?
TIM3 counts on both edges on the first signal.
The
CNT register output (1 Hz)
is completely wrong.
My configuration is:
GPIO_InitTypeDef sInitEncoderPin1;
sInitEncoderPin1.Pin = pin1Encoder.pin; // A GPIO_PIN_6
sInitEncoderPin1.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin1.Pull = GPIO_PULLUP;
sInitEncoderPin1.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin1.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
GPIO_InitTypeDef sInitEncoderPin2;
sInitEncoderPin2.Pin = pin2Encoder.pin; // A GPIO_PIN_7
sInitEncoderPin2.Mode = GPIO_MODE_AF_PP;
sInitEncoderPin2.Pull = GPIO_PULLUP;
sInitEncoderPin2.Speed = GPIO_SPEED_HIGH;
sInitEncoderPin2.Alternate = altFunctionEncoder; // GPIO_AF2_TIM3
HAL_GPIO_Init(GPIOA, &sInitEncoderPin1);
HAL_GPIO_Init(GPIOA, &sInitEncoderPin2);
encoderTimer.Init.Period = 0xffff;
encoderTimer.Init.Prescaler = 0;
encoderTimer.Init.CounterMode = TIM_COUNTERMODE_UP;
encoderTimer.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
encoderTimer.Init.RepetitionCounter = 0;
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 1);
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
encoder.IC1Filter = 0x0f;
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING; // TIM_INPUTCHANNELPOLARITY_BOTHEDGE
encoder.IC1Prescaler = TIM_ICPSC_DIV1;
encoder.IC1Selection = TIM_ICSELECTION_DIRECTTI;
encoder.IC2Filter = 0x0f;
encoder.IC2Polarity = TIM_INPUTCHANNELPOLARITY_RISING;
encoder.IC2Prescaler = TIM_ICPSC_DIV1;
encoder.IC2Selection = TIM_ICSELECTION_DIRECTTI;
HAL_TIM_Encoder_Init(&encoderTimer, &encoder);
HAL_TIM_Encoder_Start_IT(&encoderTimer, TIM_CHANNEL_ALL);
The
oscilloscope screenshot
shows a frequency of about 416 Hz.
The values shown in the
first shell output
are (very roughly!) twice as high (as the question points out already).
This appears (nearly...) correct to me since the shown configuration
encoder.EncoderMode = TIM_ENCODERMODE_TI1;
selects the "X2 resolution encoder mode", which counts 2 CNT increments per signal period.
In an application note on
timer overview,
(Sec. 4.3.4 / Fig. 7) there is an illustrative diagram how the encoder mode works in detail.
The
second screenshot
results from an incorrect TIM3 configuration:
The encoder mode (TIM_ENCODERMODE_TI1) assumes that both channels trigger only upon directed flanks in an alternating way (see the AN link above).
If one of the two channels triggers twice as many events due to
configuration
encoder.IC1Polarity = TIM_INPUTCHANNELPOLARITY_BOTHEDGE,
the counter will only count up one position and then "recognize" a "reversal" event (= change of direction).
Keeping in mind that
65535u = 0xFFFF = -1
the second screenshot only shows values -1, 0, +1 - which fits perfectly with this explanation.
The question remains why the first screenshot shows (reproducible) measurements between 800 and 822.
I assume that
the physical source of the encoder signal runs at a constant pace
the 1 Hz timer that triggered shell output is independent from TIM3, and
it has been started before the encoder timer
(i.e., above the shown code sample).
This may explain why the first two values look like nonsense (0: TIM3 has not been started yet. 545: TIM3 has been started during the shell output timer period).
Discarding the first two measurement samples, the average and standard deviation, resp., of the measured signal frequency are
808,9091 +/- 0,5950 [X2 increments per second]
404,4545 +/- 0,2975 [Hz]
which corresponds to a period of
2,4331 +/- 0,003 [ms].
Hence, the measured frequency is too low by about 11 Hz, i.e., measured period too high by nearly 30 µs, and this error is clearly beyond the statistical noise.
The question gives a hint where this error might come from:
The CNT register counts up and I read the value with 1 Hz and then I set the register to 0.
Whenever the 1 Hz "polling timer" expires, it triggers an interrupt
(or a logical event in polling software).
Processing of this interrupt/event may be delayed a little,
depending on other software (IRQ: deactivation times elsewhere in the software,
Polling: loop duration until event is polled).
Software reads CNT value.
Software resets CNT value to zero,
discarding further increments since the CNT value has been read.
TIM3 continues counting (from zero).
This hints that software needs 30 µs between (3.) and (4.), which would be quite a lot of time on an STM32F4.
Edit: I just re-checked the oscilloscope screenshot. The error is visible, but I believe it is smaller than I originally assumed (from counting flanks in the picture).

How to make oscillator-based kick drum sound exactly the same every time

I’m trying to create a kick drum sound that must sound exactly the same when looped at different tempi. The implementation below sounds exactly the same when repeated once every second, but it sounds to me like every other kick has a higher pitch when played every half second. It’s like there is a clipping sound or something.
var context = new AudioContext();
function playKick(when) {
var oscillator = context.createOscillator();
var gain = context.createGain();
oscillator.connect(gain);
gain.connect(context.destination);
oscillator.frequency.setValueAtTime(150, when);
gain.gain.setValueAtTime(1, when);
oscillator.frequency.exponentialRampToValueAtTime(0.001, when + 0.5);
gain.gain.exponentialRampToValueAtTime(0.001, when + 0.5);
oscillator.start(when);
oscillator.stop(when + 0.5);
}
for (var i = 0; i < 16; i++) {
playKick(i * 0.5); // Sounds fine with multiplier set to 1
}
Here’s the same code on JSFiddle: https://jsfiddle.net/1kLn26p4/3/
Not true; oscillator.start will begin the phase at 0. The problem is that you're starting the "when" parameter at zero; you should start it at context.currentTime.
for (var i = 0; i < 16; i++) {
playKick(context.current time + i * 0.5); // Sounds fine with multiplier set to 1
}
The oscillator is set to start at the same time as the change from the default frequency of 440 Hz to 150 Hz. Sometimes this results in a glitch as the transition is momentarily audible.
The glitch can be prevented by setting the frequency of the oscillator node to 150 Hz at the time of creation. So add:
oscillator.frequency.value = 150;
If you want to make the glitch more obvious out of curiosity, try:
oscillator.frequency.value = 5000;
and you should be able to hear what is happening.
Updated fiddle.
EDIT
In addition the same problem is interacting with the timing of the ramp. You can further improve the sound by ensuring that the setValueAtTime event always occurs a short time after playback starts:
oscillator.frequency.setValueAtTime(3500, when + 0.001);
Again, not perfect at 3500 Hz, but it's an improvement, and I'm not sure you'll achieve sonic perfection with Web Audio. The best you can do is try to mask these glitches until implementations improve. At actual kick drum frequencies (e.g. the 150 Hz in your original Q.), I can't tell any difference between successive sounds. Hopefully that's good enough.
Revised fiddle.

Unable to acquire *precisely* timed videos in Matlab (using ImgAcq toolbox)

When I try to record using the code below, the resulting videos have the correct number of frames and file lengths, but the recorded time is always slightly longer (as measured by filming a digital clock), a 60min recordings capture ~61min, and 5min recordings have extra 3-5sec (so time is skipped during recordings). Occasionally, the camera clearly show time skipping when it records for some time, then pauses for up to hour or so, and then resumes.
I am using a Basler GigE acA1300-60gm (http://www.baslerweb.com/en/products/area-scan-cameras/ace/aca1300-60gm) camera set to continuous triggering for several hours, and I need the acquired videos to have millisecond resolution. I am not sure why the recording times are so varied, am I using a wrong script for the job or does it have something to do with the hardware settings?
(Matlab R2014a on Windows 7)
vid = videoinput(adapter, deviceIDVar{1,1}, formatVar);
vid.FramesPerTrigger = NoOfFramesPerFile;
src = getselectedsource(vid);
src.FrameStartTriggerMode = 'On';
src.FrameStartTriggerSource = 'Line1';
src.FrameStartTriggerActivation = 'RisingEdge';
src.FrameStartTriggerMode = 'Off';
src.PacketSize = 8000;
triggerconfig(vid, 'hardware', 'DeviceSpecific', 'DeviceSpecific');
vid.TriggerRepeat = 0;
vid.LoggingMode = 'disk';
for i=1:FileLimit
%file path and format settings
diskLogger = VideoWriter(filenameWithExt, 'MPEG-4');
diskLogger.FrameRate = 25;
vid.DiskLogger = diskLogger;
start(vid)
wait(vid, Inf);
end
stop(vid)
delete(vid)
clear
Are here any better ways to acquire precisely timed videos (at 25FPS)? Thanks in advance!

Difference in time recorded using AVCaptureMovieFileOutput

I have recorded a movie file using AVCaptureMovieFileOutput by setting maximum duration limit.
For e.g.: If I want to record 10 seconds video, I had set the max duration and other properties for the movie file like below...
Float64 TotalSeconds = 10;
int32_t preferredTimeScale = 30
CMTime maxDuration = CMTimeMakeWithSeconds(TotalSeconds, preferredTimeScale);
aMovieFileOutput.maxRecordedDuration = maxDuration;
aMovieFileOutput.minFreeDiskSpaceLimit = 1024 * 1024;
But recorded video is showing only 9 seconds (which I played using MPMoviePlayerController), why is that time difference.. How to record exactly 10 seconds. Am I doing anything wrong while setting maximum duration. Thanx.
Please be sure to have the good framerate for the output
#define CAPTURE_FRAMES_PER_SECOND 30
//SET THE CONNECTION PROPERTIES (output properties)
AVCaptureConnection* captureConnection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
if(captureConnection.supportsVideoMinFrameDuration) captureConnection.videoMinFrameDuration = CMTimeMake(1,CAPTURE_FRAMES_PER_SECOND);
if(captureConnection.supportsVideoMaxFrameDuration) captureConnection.videoMaxFrameDuration = CMTimeMake(1,CAPTURE_FRAMES_PER_SECOND);
CMTimeShow(captureConnection.videoMinFrameDuration);
CMTimeShow(captureConnection.videoMaxFrameDuration);

Visualizing Sine Wave with Processing

I have 1000+ row Sine Wave data which changes with time and I want to visualize it with Processing language. My aim is to create an animation which will draw a Sine Wave with time starting from the middle of the rectangular [height/2]. I also want to show only the 1 second periods of that wave. I mean after 1 second, first coordinate should dissappear, and so forth.
How can I achieve that ?
Thanks
Sample Data :
TIME X Y
0.1333 0 0
0.2666 0.1 0.0999983333
0.3999 0.2 0.1999866669
0.5332 0.3 0.299955002
0.6665 0.4 0.3998933419
0.7998 0.5 0.4997916927
0.9331 0.6 0.5996400648
1.0664 0.7 0.6994284734
The way you'd achieve that is to split this project into tasks:
load & parse data
update time and render data
To make sure part 1 goes smoothly it's probably best to make sure your data is easy to parse first. The sample data looks like a table/spreadsheet, but it's not formatted with a standard separator(e.g. comma or tab). You can fiddle things when you parse, but I recommend using clean data first, for example, if you plan on using space as a separator:
TIME X Y
0.1333 0.0 0
0.2666 0.1 0.0999983333
0.3999 0.2 0.1999866669
0.5332 0.3 0.299955002
0.6665 0.4 0.3998933419
0.7998 0.5 0.4997916927
0.9331 0.6 0.5996400648
1.0664 0.7 0.6994284734
Once that's done, you can use loadStrings() to load the data and split() to break a row into 3 elements which can be converted from string to float.
Once you've got value to use, you can store them. You can either create three arrays, each holding a field from the loaded data(one for all the X values, one for all the Y values and one for all the time values) or you can cheat and use a single array of PVector objects. Although PVector is meant for 3D math/linear algebra, you have 2D coordinates, so you can store time as 3rd 'dimension'/component.
Part two revolves mostly around updating based on time, and this is where millis() comes in handy. You can check the amount of time passed between updates and if it's greater than a certain (delay) value, it's time for another update (of the frame/data row index).
The last part you need to worry about is rendering the data on screen. Luckily in your sample data the coordinates are normalized(between 0.0 and 1.0) which makes easy to map to the sketch dimensions(by using simple multiplication). Otherwise the map() function comes in handy.
Here's a sketch to illustrate the above, data.csv is a text file containing the formatted sample data from above:
PVector[] frames;//keep track of the frame data(position(x,y) and time(store in PVector's z property))
int currentFrame = 0,totalFrames;//keep track of the current frame and total frames from the csv
int now, delay = 1000;//keep track of time and a delay to update frames
void setup(){
//handle data
String[] rows = loadStrings("data.csv");//load data
totalFrames = rows.length-1;//get total number of lines (-1 = sans the header)
frames = new PVector[totalFrames];//initialize/allocate frame data array
for(int i = 1 ; i <= totalFrames; i++){//start parsing data(from 1, skip header)
String[] frame = rows[i].split(" ");//chop each row into 3 strings(time,x,y)
frames[i-1] = new PVector(float(frame[1]),float(frame[2]),float(frame[0]));//parse each row(not i-1 to get back to 0 index) and how the PVector's initialized 1,2,0 (x,y,time)
}
now = millis();//initialize this to keep track of time
//render setup, up to you
size(400,400);smooth();fill(0);strokeWeight(15);
}
void draw(){
//update
if(millis() - now >= delay){//if the amount of time between the current millis() and the last time we updated is greater than the delay (i.e. every 'delay' ms)
currentFrame++;//update the frame index
if(currentFrame >= totalFrames) currentFrame = 0;//reset to 0 if we reached the end
now = millis();//finally update our timer/stop-watch variable
}
PVector frame = frames[currentFrame];//get the data for the current frame
//render
background(255);
point(frame.x * width,frame.y * height);//draw
text("frame index: " + currentFrame + " data: " + frame,mouseX,mouseY);
}
There are a couple of extra notes needed:
You mentioned moving to the next coordinate after 1 second. From what I can see in your sample data there are 8 updates per second, so 1000/8 would probably work better. It's up to you how you handle timing though.
I assume your full set includes data for a sine wave movement. I've mapped to the full coordinates, but in the render part of the draw() loop you can map however you like(e.g. including a height/2 offset, etc.). Also if you're not familiar with sine waves, have a look at these Processing resources: Daniel Shiffman's SineWave sample, Ira Greenberg's trig tutorial.