Is it possible to change the volume of a WAV file while playing. I use teensy 3.5, the DAC0 pin as the output and amplified speakers connected to DAC0 pin. Also I use an HC-SR04 distance sensor to measure the distance and I want to change the volume while the file is playing according to the distance. My code below doesn't affect the sound volume.
Code:
#include <NewPing.h>
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
AudioPlaySdWav playWav1;
AudioOutputAnalog audioOutput;
AudioConnection patchCord1(playWav1, 0, audioOutput, 0);
AudioConnection patchCord2(playWav1, 1, audioOutput, 1);
AudioControlSGTL5000 sgtl5000_1;
// Use these with the Teensy 3.5 & 3.6 SD card
#define SDCARD_CS_PIN BUILTIN_SDCARD
#define SDCARD_MOSI_PIN 11 // not actually used
#define SDCARD_SCK_PIN 13 // not actually used
#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 300
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float vol;
int distance;
void setup()
{
delay(500);
Serial.begin(9600);
// Audio connections require memory to work. For more
// detailed information, see the MemoryAndCpuUsage example
AudioMemory(8);
// Comment these out if not using the audio adaptor board.
// This may wait forever if the SDA & SCL pins lack
// pullup resistors
//sgtl5000_1.enable();
// sgtl5000_1.volume(0.5);
SPI.setMOSI(SDCARD_MOSI_PIN);
SPI.setSCK(SDCARD_SCK_PIN);
if (!(SD.begin(SDCARD_CS_PIN))) {
// stop here, but print a message repetitively
while (1) {
Serial.println("Unable to access the SD card");
delay(500);
}
}
}
void playFile(const char *filename)
{
Serial.print("Playing file: ");
Serial.println(filename);
// Start playing the file. This sketch continues to
// run while the file plays.
playWav1.play(filename);
// A brief delay for the library read WAV info
delay(5);
// Simply wait for the file to finish playing.
while (playWav1.isPlaying()) {
// uncomment these lines if you audio shield
// has the optional volume pot soldered
//float vol = analogRead(15);
//vol = vol / 1024;
delay(50); // Wait 50ms between pings
distance = sonar.ping_cm();
vol = map(distance,MAX_DISTANCE, 1, 0.1, 0.8);
Serial.println(vol);
sgtl5000_1.volume(vol);
}
}
void loop()
{
playFile("SOUND.WAV"); // filenames are always uppercase 8.3 format
}