YIN-Frequency-Detection and overtones (guitar strings) - c

I'm developing an IOS app for frequency detection, and I'm using the YIN algorithm, which is very precise: witch Audacity, I've generated rectangular waves of different frequencies - and my algorithm has a precision of about 0.1 % - for example generating a tone of 82,4 Hz (E string), I really get 82,4 Hz and nothing else.
Anyhow, when I strum a guitar string, I often get overtones which sometimes can be stronger (with a higher amplitude) than the fundamental tone (F0). Consequently, my display starts "dancing" and toggling - sometimes, it even occurs that (when the tone dies out) my algorithm stops at the overtone's frequency (for example A instead of E) - so the user has to strum the string again in oder to see if his desired tone (frequency) is present.
I know that this phenomena has nothing to do with my algorithm, because it's merely a "hardware" problem (I mean the guitar which simply produces overtones).
I've tried in vain to smooth the results (of the frequency detection) or to "snap" to a fixed frequency as soon as a crucial frequency (for example 82.4 Hz for E string +/- tolerance) has been detected. Anyhow, it often occurrs that my algorithm snaps into an erroneous frequency, as well.
I'm asking myself how cheap guitar tuners (for 10$ in guitar stores) are working, as their frequency detections are reliable and stable, as well.
I don't want to change the algorithm, but two possible solutions come into my mind:
Preprocessing of the signal (maybe Hanning window, lowpass or bandpass filtering) and/or
Postprocessing of the signal (some kind of frequency smoothing).
Has someone an idea how to overcome the "choppy" results?

I used autocorrelation for my free chromatic app iTransposer and incorporated a Hanning window so this may help you. I wasn't looking for accuracy initially as I wanted to display the note on a stave not a meter. However a friend of mine tested it to 0.1 Hz with a signal generator at his work and had issues over 383 Hz with simple signals such as Sine waves.I've tried it with various brass instruments, guitar and Garageband instruments seems to be OK for tuning.
Basically I implemented this http://www.ucl.ac.uk/~ucjt465/tutorials/praatpitch.html
using VDSP and updated a sample project supplied by Kevin P Murphy https://github.com/kevmdev/PitchDetectorExample

Related

Audio oscillator with (bi)cubic interpolation

This question is about interpolating sine wave oscillators:
Assuming that amplitude and frequency trajectories for a sine wave are defined by corresponding breakpoint functions or read from user interface, the following few lines of C-code show a common sine-wave oscillator paradigm for synthesizing inNumberFrames of mono audio samples in real time, using linear interpolation:
// ... (pre-computing initial amplitude and phase values)...
for (UInt32 frame = 0; frame < inNumberFrames; frame++)
{
buffer[frame] = sinf(phasef) * ampf[frame];
phasef += osc->previousPartialPhaseIncrementf + df*frame;
if (phasef > TWO_PI) phasef -= TWO_PI;
}
// ... (storing current amplitude and phase values)...
While musically satisfying in general (although it can be performance optimized using pre-computed sine wavetables and pointer arithmetics), there are occasions when linear interpolation artifacts can be heard. I'd like to know is there a free example of cubic or bicubic interpolation of amplitude and phase oscillator instantaneous values? Concerning that the render thread has real-time priority (at least in CoreAudio), it is important to keep it lightweight, also to avoid running into too many lower-priority threading issues if interpolating outside the render thread. I'd be thankful to anyone pointing me at a working example of a (bi)cubic interpolation sine-wave oscillator algorithm in C, no matter how simple (or complex) it is.
Thanks in advance.
UPDATE:
Perhaps this illustration can clarify what was meant by values to be interpolated. Purple dots represent a frequency envelope breakpoint curve (connected by linear interpolation). Cyan dots represent a possibility of superimposed polynomial interpolations. First and last segments are off-scale:
Have a look at musicdsp.org where there is a post on (almost) Ready-to-use oscillators. The end of the post contains the method that you might be interested in with the following signature (by Ollie N.)
float Oscillator::UpdateWithCubicInterpolation( float frequency )

Obtaining orientation with 3-axis accelerometer and gyro

This is my first post on SO. I haven't already developed much code for embedded systems, but I have few problems and need help from more advanced programmers. I use following devices:
- LandTiger board with LPC1768 (Cortex M3) MCU,
- Digilent pmodACL with ADXL345 accelerometer (3 axis),
- Digilent pmodGYRO with L3G4200D gyroscope (3 axis).
I would like to get some information about device orientation, i.e. rotation angles over X, Y and Z axes. I've read that in order to achieve this I need to combine data from both accelerometer and gyroscope using Kallman filter or its simpler form i.e. complementary filter. I would like to know if it's possible to count roll, pitch and yaw from full range (0-360 degrees) using measurment data only from gyroscope and accelerometer (without magnetometer). I've also found some mathematical formulas (http://www.ewerksinc.com/refdocs/Tilt%20Sensing%20with%20LA.pdf and http://www.freescale.com/files/sensors/doc/app_note/AN3461.pdf) but they contain root squares in numerators/denominators so the information about proper quadrant of coordinate system is lost.
The question you are asking is a fairly frequent one, and is fairly complex, with many different solutions.
Although the title mentions only an accelerometer, the body of your post mentions a gyroscope, so I will assume you have both. In addition there are many steps to getting low-cost accelerometers and gyros to work, one of those is to do the voltage-to-measurement conversion. I will not cover that part.
First and foremost I will answer your question.
You asked if by 'counting' the gyro measurements you can estimate the attitude (orientation) of the device in Euler Angles.
Short answer: Yes, you could sum the scaled gyro measurements to get a very noisy estimate of the device rotation (actual radians turned, not attitude), however it would fail as soon as you rotate more than one axis. This will not suffice for most applications.
I will provide you with some general advise, specific knowledge and some example code that I have used before.
Firstly, you should not try to solve this problem by writing a program and testing with your IMU. You should start by writing a simulation using validated libraries, then validate your algorithm/program, and only then try to implement it with the IMU.
Secondly, you say you want to "count roll, pitch and yaw from full range (0-360 degrees)".
From this I assume you mean you want to be able to determine the Euler Angles that represent the attitude of the device with respect to an external stationary North-East-Down (NED) frame.
Your statement makes me think you are not familiar with representations of attitude, because as far as I know there are no Euler Angle representations with all 3 angles in the 0-360 range.
The application for which you want to use the attitude of the device will be important. If you are using Euler Angles you will not be able to accurately track the attitude of the device when large (greater than around 50 degrees) rotations are made on the roll or pitch axes, due to what is known as Gimbal Lock.
If you require the tracking of such motions then you will need to use a quaternion or Direction Cosine Matrix (DCM) representation of attitude.
Thirdly, as you have said you can use a Complimentary Filter or Kalman Filter variant (Extended Kalman Filter, Error-State Kalman Filter, Indirect Kalman Filter) to accurately track the attitude of the device by fusing the data from the accelerometer, gyro and a magnetometer. I suggest the Complimentary Filter described by Madgwick which is implemented in C, C# and MATLAB here. A Kalman Filter variant would be necessary if you wanted to track the position of the device, and had an additional sensor such as GPS.
For some example code of mine using accelerometer only to get Euler Angle pitch and roll see my answer to this other question.

Mobile geolocation precision - cordova / phonegap

I want to develop an app that detects how far the user/device is from points on a map.
Calculating the distance is easy, but when you get close to about 30meters I would need it to be as precise as possible.
Basically I want some lights on the UI to get brighter the closer you get to the target/point.
How do I achieve this if the gps position sometimes bounces around for 5-10 meters or more?
Any ideas on how to approach this?
Thanks!
In general there is the inaccuracy with the position, and indeed its meters, thus the bouncing will be there and its rather impossible to get rid of it, anyways, one suggestion would be to collect the last few (3-10 up to you and your logic really) locations and calculate average from them. Then with fast movements your position would be lagging of course, but when doing slow movements the position shown should be more stable.. Of course you could also have additional logic on determining the movement direction, and accepting the location change towards that faster etc.
You will not get a better precision than 3m to the target.
At low, speed, like walking, you will no make it better than 8-10m.
Count the distance sicne last used fix, If it exceeds 12m then use the fix, and mark it as last used.
This is a simple filter which works well for walking speeds.
At speeds higher (> 10km/h) switch off the filter.
GPS should not jump at that speed.

Signal classification - recognise a signal with AI

I have a problem with recognising a signal. Let say the signal is a quasiperiodic signal, the period time has finite limits. The "shape" of the signal must match some criteria, so the actual algorithm using signal processing techniques such as filtering, derivating the the signal, looking for maximum and minimum values. It has a good rate at finding the good signals, but the problem is it also detects wrong shapes too.
So I want to use Aritifical Intelligence - mainly Neural Networks - to overcome this problem. I thought that a multi layer network with some average inputs (the signal can be reduced) and one output whould shows the "matching" from 0..1. However the problem is that I never did such a thing, so I am asking for help, how to achive something like this? How to teach the neural network to get the expected results? (let say I have vectors for inputs which should give 1 as output)
Or this whole idea is a wrong approximation for the problem? I am open to any learning algorithms or idea to learn and use to overcome on this problem.
So here is a figure on the measured signal(s) (values and time is not a concern now) and you can see a lot "wrong" ones, the most detected signals are good as mentioned above.
Your question can be answered in a broad manner. You should consider editing it to prevent it to be closed.
But anyway, Matlab had a lot of built-in function and toolbox to support Artificial Intelligence, with a lot of sample code available, which you can modify and refer to. You can find some in Matlab FileExchange.
And I know reading a lot of technical paper for Artificial Intelligence is a daunting task, so good luck!
You can try to build a neural network using Neuroph. You can inspire from "http://neuroph.sourceforge.net/TimeSeriesPredictionTutorial.html".
On the other hand, it is possible to approximate the signal using Fourier transformation.
You can try 1D convolution. So the basic idea is you give a label 0: bad, 1: good to each signal value at each timestamp. After this, you can model
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', padding = 'same', input_shape=(1,1)))
model.add(Bidirectional(LSTM(20, return_sequences=True)))
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', padding = 'same'))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(100, activation='sigmoid'))
model.add(Dense(2, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
Train the model and then give it a new signal to predict. It will predict given series to 0 and 1 values. if count of 0 is more than count of 1, the signal is not good.

Given an audio stream, find when a door slams (sound pressure level calculation?)

Not unlike a clap detector ("Clap on! clap clap Clap off! clap clap Clap on, clap off, the Clapper! clap clap ") I need to detect when a door closes. This is in a vehicle, which is easier than a room or household door:
Listen: http://ubasics.com/so/van_driver_door_closing.wav
Look:
It's sampling at 16bits 4khz, and I'd like to avoid lots of processing or storage of samples.
When you look at it in audacity or another waveform tool it's quite distinctive, and almost always clips due to the increase in sound pressure in the vehicle - even when the windows and other doors are open:
Listen: http://ubasics.com/so/van_driverdoorclosing_slidingdoorsopen_windowsopen_engineon.wav
Look:
I expect there's a relatively simple algorithm that would take readings at 4kHz, 8 bits, and keep track of the 'steady state'. When the algorithm detects a significant increase in the sound level it would mark the spot.
What are your thoughts?
How would you detect this event?
Are there code examples of sound pressure level calculations that might help?
Can I get away with less frequent sampling (1kHz or even slower?)
Update: Playing with Octave (open source numerical analysis - similar to Matlab) and seeing if the root mean square will give me what I need (which results in something very similar to the SPL)
Update2: Computing the RMS finds the door close easily in the simple case:
Now I just need to look at the difficult cases (radio on, heat/air on high, etc). The CFAR looks really interesting - I know I'm going to have to use an adaptive algorithm, and CFAR certainly fits the bill.
-Adam
Looking at the screenshots of the source audio files, one simple way to detect a change in sound level would be to do a numerical integration of the samples to find out the "energy" of the wave at a specific time.
A rough algorithm would be:
Divide the samples up into sections
Calculate the energy of each section
Take the ratio of the energies between the previous window and the current window
If the ratio exceeds some threshold, determine that there was a sudden loud noise.
Pseudocode
samples = load_audio_samples() // Array containing audio samples
WINDOW_SIZE = 1000 // Sample window of 1000 samples (example)
for (i = 0; i < samples.length; i += WINDOW_SIZE):
// Perform a numerical integration of the current window using simple
// addition of current sample to a sum.
for (j = 0; j < WINDOW_SIZE; j++):
energy += samples[i+j]
// Take ratio of energies of last window and current window, and see
// if there is a big difference in the energies. If so, there is a
// sudden loud noise.
if (energy / last_energy > THRESHOLD):
sudden_sound_detected()
last_energy = energy
energy = 0;
I should add a disclaimer that I haven't tried this.
This way should be possible to be performed without having the samples all recorded first. As long as there is buffer of some length (WINDOW_SIZE in the example), a numerical integration can be performed to calculate the energy of the section of sound. This does mean however, that there will be a delay in the processing, dependent on the length of the WINDOW_SIZE. Determining a good length for a section of sound is another concern.
How to Split into Sections
In the first audio file, it appears that the duration of the sound of the door closing is 0.25 seconds, so the window used for numerical integration should probably be at most half of that, or even more like a tenth, so the difference between the silence and sudden sound can be noticed, even if the window is overlapping between the silent section and the noise section.
For example, if the integration window was 0.5 seconds, and the first window was covering the 0.25 seconds of silence and 0.25 seconds of door closing, and the second window was covering 0.25 seconds of door closing and 0.25 seconds of silence, it may appear that the two sections of sound has the same level of noise, therefore, not triggering the sound detection. I imagine having a short window would alleviate this problem somewhat.
However, having a window that is too short will mean that the rise in the sound may not fully fit into one window, and it may apppear that there is little difference in energy between the adjacent sections, which can cause the sound to be missed.
I believe the WINDOW_SIZE and THRESHOLD are both going to have to be determined empirically for the sound which is going to be detected.
For the sake of determining how many samples that this algorithm will need to keep in memory, let's say, the WINDOW_SIZE is 1/10 of the sound of the door closing, which is about 0.025 second. At a sampling rate of 4 kHz, that is 100 samples. That seems to be not too much of a memory requirement. Using 16-bit samples that's 200 bytes.
Advantages / Disadvantages
The advantage of this method is that processing can be performed with simple integer arithmetic if the source audio is fed in as integers. The catch is, as mentioned already, that real-time processing will have a delay, depending on the size of the section that is integrated.
There are a couple of problems that I can think of to this approach:
If the background noise is too loud, the difference in energy between the background noise and the door closing will not be easily distinguished, and it may not be able to detect the door closing.
Any abrupt noise, such as a clap, could be regarded as the door is closing.
Perhaps, combining the suggestions in the other answers, such as trying to analyze the frequency signature of the door closing using Fourier analysis, which would require more processing but would make it less prone to error.
It's probably going to take some experimentation before finding a way to solve this problem.
You should tap in to the door close switches in the car.
Trying to do this with sound analysis is overengineering.
There are a lot of suggestions about different signal processing
approaches to take, but really, by the time you learn about detection
theory, build an embedded signal processing board, learn the processing
architecture for the chip you chose, attempt an algorithm, debug it, and then
tune it for the car you want to use it on (and then re-tune and re-debug
it for every other car), you will be wishing you just stickey taped a reed
switch inside the car and hotglued a magnet to the door.
Not that it's not an interesting problem to solve for the dsp experts,
but from the way you're asking this question, it's clear that sound
processing isn't the route you want to take. It will just be such a nightmare
to make it work right.
Also, the clapper is just an high pass filter fed into a threshold detector. (plus a timer to make sure 2 claps quickly enough together)
There is a lot of relevant literature on this problem in the radar world (it's called detection theory).
You might have a look at "cell averaging CFAR" (constant false alarm rate) detection. Wikipedia has a little bit here. Your idea is very similar to this, and it should work! :)
Good luck!
I would start by looking at the spectral. I did this on the two audio files you gave, and there does seem to be some similarity you could use. For example the main difference between the two seems to be around 40-50Hz. My .02.
UPDATE
I had another idea after posting this. If you can, add an accelerometer onto the device. Then correlate the vibrational and acoustic signals. This should help with cross vehicle door detection. I'm thinking it should be well correlated since the sound is vibrationally driven, wheres the stereo for example, is not. I've had a device that was able to detect my engine rpm with a windshield mount (suction cup), so the sensitivity might be there. (I make no promises this works!)
(source: charlesrcook.com)
%% Test Script (Matlab)
clear
hold all %keep plots open
dt=.001
%% Van driver door
data = wavread('van_driver_door_closing.wav');
%Frequency analysis
NFFT = 2^nextpow2(length(data));
Y = fft(data(:,2), NFFT)/length(data);
freq = (1/dt)/2*linspace(0,1,NFFT/2);
spectral = [freq' 2*abs(Y(1:NFFT/2))];
plot(spectral(:,1),spectral(:,2))
%% Repeat for van sliding door
data = wavread('van_driverdoorclosing.wav');
%Frequency analysis
NFFT = 2^nextpow2(length(data));
Y = fft(data(:,2), NFFT)/length(data);
freq = (1/dt)/2*linspace(0,1,NFFT/2);
spectral = [freq' 2*abs(Y(1:NFFT/2))];
plot(spectral(:,1),spectral(:,2))
The process for finding distinct spike in audio signals is called transient detection. Applications like Sony's Acid and Ableton Live use transient detection to find the beats in music for doing beat matching.
The distinct spike you see in the waveform above is called a transient, and there are several good algorithms for detecting it. The paper Transient detection and classification in energy matters describes 3 methods for doing this.
I would imagine that the frequency and amplitude would also vary significantly from vehicle to vehicle. Best way to determine that would be taking a sample in a Civic versus a big SUV. Perhaps you could have the user close the door in a "learning" mode to get the amplitude and frequency signature. Then you could use that to compare when in usage mode.
You could also consider using Fourier analysis to eliminate background noises that aren't associated with the door close.
Maybe you should try to detect significant instant rise in air pressure that should mark a door close. You can pair it with this waveform and sound level analysis and these all might give you a better result.
On the issue of less frequent sampling, the highest sound frequency which can be captured is half of the sampling rate. Thus, if the car door sound was strongest at 1000Hz (for example) then a sampling rate below 2000Hz would lose that sound entirely
A very simple noise gate would probably do just fine in your situation. Simply wait for the first sample whose amplitude is above a specified threshold value (to avoid triggering with background noise). You would only need to get more complicated than this if you need to distinguish between different types of noise (e.g. a door closing versus a hand clap).

Resources