Can you give me an example for this MATLAB snippet to generate sine wav with specified phase?

function synthesize_fp(file,f,d,p,gamma)
% Matlab function synthesize_fp(file,f,d,p,gamma) 
% creates a .wav audio file of a sound where all frequencies, 
% amplitudes(power) and phase may be specified.
% file is a string which is the name of the .wav file.
% f is a length n vector of frequencies in Hz
% d is the duration in seconds
% p is a length n vector of amplitudes
% gamma is a length n vector of phase shifts, as a fraction of the 
%  period of the first harmonic f1.
% Mark R. Petersen, U. of Colorado Boulder Applied Math Dept, Feb 2004

Fs=22050; nbits=8;              % frequency and bit rate of wav file

t = linspace(1/Fs, d, d*Fs);    % time
y = zeros(1,Fs*d);              % initialize sound data
for j=1:length(p);
  y = y + p(j)*cos(2*pi*f(j)*(t-gamma(j)/f(1))); % sythesize waveform
y = .5*y/max(y);                % normalize.  Coefficent controls volume.
wavwrite( y, Fs, nbits, file)

This is a programming question (won't benefit anyone apart from you) and what's more, you are using program rather different from application you described. In order to generate the sinusoidal wave with given phase you don't need to use that. Above script is used mainly for synthesis of a wave with harmonic content depending on type of sound (flute, violin, etc), and personally I don't like it as it is terribly written using a for loop.

For general answer you can refer to Phase information. Additionally usage description is very clear - did you tried to follow it? For example more complicated sound would be defined as:

file = 'output.wav';
f = [100 200 300 400];
d = 5;
p = [1 0.5 0.25 0.124];
gamma = zeros(1, 4); % Start with no phase-shift

For pure cosinusoid use the:

file = 'output.wav';
f = 100
d = 5;
p = 1;
gamma = 0;

Application of phase shift is not very straightforward as its described by relative shift with respect to fundamental frequency. Therefore I rather suggest to write it on your own and keep it clean:

fs = 400; % sampling frequency
d = 1; % duration
f = 10; % wave frequency
phi = pi/2; % phase shift - will produce cosinusoid for pi/2
t = linspace(1/fs, d, d*fs); % time vector
y = sin(2*pi*f*t + phi);
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.