Code:
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
// GUItool: begin automatically generated code
AudioInputUSB usb1; //xy=285.00000381469727,266.00000381469727
AudioSynthWaveformSine sine1; //xy=285.00000381469727,317.0000047683716
AudioSynthWaveformSine sine2; //xy=294,369
AudioAnalyzeRMS rms1; //xy=720,201
AudioMixer4 mixer1; //xy=580,292
AudioOutputAnalog dac1; //xy=851,261
AudioConnection patchCord1(usb1, 0, mixer1, 0);
AudioConnection patchCord2(usb1, 0, rms1, 0);
AudioConnection patchCord5(usb1, 1, mixer1, 1);
AudioConnection patchCord6(sine1, 0, mixer1, 2);
AudioConnection patchCord7(sine2, 0, mixer1, 3);
AudioConnection patchCord8(mixer1, dac1);
// GUItool: end automatically generated code
float vol;
void setup() {
AudioMemory(12);
Serial.begin(9600);
analogReference(EXTERNAL);
vol = usb1.volume();
sine1.amplitude(0.2);
sine1.frequency(1000);
sine2.amplitude(0.2);
sine2.frequency(1000);
//Mixer begins "off"
mixer1.gain(0, 0);
mixer1.gain(1, 0);
mixer1.gain(2, 0);
mixer1.gain(3, 0);
while(Serial.available()) {}
Serial.println("setup done");
}
float x; //Temporary variable to read RMS
int s = 0; //STATUS Variable, 1 means the audio from the PC is playing, 0 is not
void loop() {
x = rms1.read();
if(x != 0.0 && s == 0) { //If a change is detected, toggle the mixer
sine2.phase(180);
Serial.println("Changed.");
x = 0.0;
s = 1;
}
if(s == 1) {
vol = usb1.volume();
sine2.amplitude(vol);
mixer1.gain(0, 0.5);
mixer1.gain(1, 0);
mixer1.gain(3, 0.5);
} else { //If the USB audio is not being played, just output a sine wave
mixer1.gain(0, 0);
mixer1.gain(2, 0);
mixer1.gain(3, 1);
}
}
Several things to note: the amplitude of the generated sine wave is set to 0.2 because that's the amplitude of the sine wave I'm playing as USB Audio. If you run this on your own and use a different sine wave, change the amplitude and frequency accordingly. In addition, I currently use the RMS analyze feature to detect when the USB audio begins playing, but if you have any suggestions on how to better detect the PC's music being played or paused, please let me know.