Tuesday, May 8, 2012

combine two sound files to add a "background" soundtrack to a foreground sound.

//This lab will have you combine two sound files to add a "background" soundtrack to a foreground sound.
 //The following files of the Gettysburg Address and the Preamble of the U.S. Constitution are great
 //foreground sound files.






public class Lab13
{

public static void main (String args[])
{
System.out.println("Begin Java Execution");
System.out.println("");

// put your Java Program here

// pick the first file.
String filename = FileChooser.pickAFile();
Sound foregroundSound = new Sound (filename);

// pick the background sound file.
String filename2 = FileChooser.pickAFile();
Sound backgroundSound = new Sound (filename2);

// combine the sounds
// Call a method to combine the two sounds
Sound s3;
s3 = combinesound (foregroundSound, backgroundSound);
// Play the sound
//s3.play();

s3.explore();

// save the new sound file

String saveFilename = FileChooser.pickAFile ();
s3.write (saveFilename);


System.out.println("");
System.out.println("End Java Execution");

}
// Start a combinesound method.

public static Sound combinesound (Sound foregroundSound, Sound backgroundSound)
{
SoundSample[] fg = foregroundSound.getSamples();
SoundSample[] bg = backgroundSound.getSamples();

// set length3 to the length of the shorter sound
int length3;
if ( fg.length < bg.length )
length3 = fg.length;
else
length3 = bg.length;

Sound s3 = new Sound (length3);
SoundSample[] ssarr3 = s3.getSamples();

int pos;

for ( pos = 0 ; pos < ssarr3.length ; pos++ )
{
int amplitude1 = fg[pos].getValue();
int bgp = pos;

while ( bgp >= bg.length )
{
bgp = bgp - bg.length ;
}

int amplitude2 = (bg[bgp].getValue())/3;

// combine the two amplitudes (add them together)
int amplitude3 = amplitude1 + amplitude2;

// check for clipping and resolve
if ( amplitude3 > 32767 )
{
amplitude3 = 32767;
}
if ( amplitude3 < -32768 )
{
amplitude3 = -32768;
}

// store the new amplitude value into sounnd s3
ssarr3[pos].setValue (amplitude3);
}

return s3;
}


} // end of Template class

No comments:

Post a Comment