### scale2.r ### R program to play a scale with a matrix for storage ### author: Ian Knopke, for I400 at IU, Feb 2007 library(tuneR) ##needed for playback sr = 8000 bits = 16 ##reference pitch of A 440 f0=440 ##symbolically store a melody as a matrix ##the first value is the pitch ##the second value in each row is the duration ##at the bottom, 2 is the number of things ##we have pitch and duration, so that's 2 ##the 8 is the number of notes notes<-matrix( c( 0, 1, 2, 1, 4, 2, 5, 1, 7, 1, 9, 2, 11, 1, 12, 1 ),2,8) ##now we assign each column to a different name ##and it works the same as before pitches=notes[1,] durations=notes[2,] ##print these out if you feel like it print(pitches) print(durations) ##how to get both plots onto one screen par(mfrow=c(2,1)) plot(pitches) plot(durations) ##setup a blank array called freqlist to hold the output sound total_length=sum(durations)*sr freqlist=rep(0,total_length) ##index for the output file lastend=0 ##now go through each note and build a sine wave for(i in 1:length(pitches)){ ##calculate the frequency from the pitch note_freq=f0*2^(pitches[i]/12) ##calculates the note duration in samples note_dur=durations[i]*sr-1 ##we need to keep an index into the output sound array ##this just figures out where to start putting the sine wave ##and where to stop startindex=lastend+1 endindex=startindex+note_dur ##uncomment these to see how the indexes work #print(i) #print(startindex) #print(endindex) ##make the time index for this sine wave t_singlenote=seq(0,note_dur)/sr ##...and the sine wave note=sin(2*pi*note_freq*t_singlenote) ##now stick our new note into the output array freqlist[startindex:endindex]=note ##we need to know where we left off in the output array ##so we save that for next time lastend=endindex } ##ok, so now we've made up our output file and we just ##need to play it u=Wave(2^(bits-4)*freqlist,samp.rate=sr,bit=16) play(u,"play");