import java.io.*; import javax.sound.sampled.*; import java.util.Random; /** * Class CrowdAudioPlayer. This class chooses a random crowd file to be * outputted to the viewers and deals with all the underlying audio processing. * This runs in a seperate thread to enable multiple files to be read * simultaneously during a match. * * * @author Adrien Martel * */ public class CrowdAudioPlayer extends Thread { private static final int external_buffer_size = 128000; private String[] chants = { "000050.wav", "000051.wav", "000053.wav", "000054.wav", "000055.wav", "000057.wav", "000059.wav", "000060.wav", "000062.wav", "000064.wav", "crowd1.wav", "crowd2.wav", "crowd3.wav", "crowd4.wav", "crowd5.wav" }; private boolean loop = true; public CrowdAudioPlayer(String[] crowds, boolean loop) { chants = crowds; //if loop is true then this class will continue playing //other randomly selected crowd audio files this.loop = loop; } /** * * Overriden Run method. Randomly selects the next file to be read * from the array of files and carried out all the audio processing * to output the audio to the viewers. * */ public void run() { boolean firstrun = true; Random rand = new Random(); //randomly get an index to retrieve the next file int index = Math.round(rand.nextInt(chants.length)); String strfilename = chants[index]; File dir = new File("Sounds"); File soundfile = new File(dir, strfilename); SourceDataLine line = null; while (true) { AudioInputStream audioinputstream = null; try { audioinputstream = AudioSystem.getAudioInputStream(soundfile); } catch (Exception e) { e.printStackTrace(); System.exit(1); } AudioFormat audioformat = audioinputstream.getFormat(); if (firstrun) { DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioformat); try { line = (SourceDataLine) AudioSystem.getLine(info); line.open(audioformat); } catch (LineUnavailableException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.exit(1); } line.start(); } int nbytesread = 0; byte[] abdata = new byte[external_buffer_size]; while (nbytesread != -1) { try { nbytesread = audioinputstream .read(abdata, 0, abdata.length); } catch (IOException e) { e.printStackTrace(); } if (nbytesread >= 0) { int nbyteswritten = line.write(abdata, 0, nbytesread); } } line.drain(); firstrun = false; // We only need to play this crowd type once, leave the loop if (!loop) { line.close(); break; } // get next sound randomly index = Math.round(rand.nextInt(chants.length)); strfilename = chants[index]; soundfile = new File(dir, strfilename); } } }