USBAudio speaker example
main.cpp
- Committer:
- samux
- Date:
- 2013-03-01
- Revision:
- 9:a7a9d8e8a740
- Parent:
- 7:ba4f65ce69f2
File content as of revision 9:a7a9d8e8a740:
// USBAudio speaker example
#include "mbed.h"
#include "USBAudio.h"
// frequency: 48 kHz
#define FREQ 48000
// 1 channel: mono
#define NB_CHA 1
// length of an audio packet: each ms, we receive 48 * 16bits ->48 * 2 bytes. as there is one channel, the length will be 48 * 2 * 1
#define AUDIO_LENGTH_PACKET 48 * 2 * 1
// USBAudio (we just use audio packets received, we don't send audio packets to the computer in this example)
USBAudio audio(FREQ, NB_CHA, 8000, 1, 0x7180, 0x7500);
// speaker connected to the AnalogOut output. The audio stream received over USb will be sent to the speaker
AnalogOut speaker(p18);
// ticker to send data to the speaker at the good frequency
Ticker tic;
// buffer where will be store one audio packet (LENGTH_AUDIO_PACKET/2 because we are storing int16 and not uint8)
int16_t buf[AUDIO_LENGTH_PACKET/2];
// show if an audio packet is available
volatile bool available = false;
// index of the value which will be send to the speaker
int index_buf = 0;
// previous value sent to the speaker
uint16_t p_val = 0;
// function executed each 1/FREQ s
void tic_handler() {
float speaker_value;
if (available) {
//convert 2 bytes in float
speaker_value = (float)(buf[index_buf]);
// speaker_value between 0 and 65535
speaker_value += 32768.0;
// adjust according to current volume
speaker_value *= audio.getVolume();
// as two bytes has been read, we move the index of two bytes
index_buf++;
// if we have read all the buffer, no more data available
if (index_buf == AUDIO_LENGTH_PACKET/2) {
index_buf = 0;
available = false;
}
} else {
speaker_value = p_val;
}
p_val = speaker_value;
// send value to the speaker
speaker.write_u16((uint16_t)speaker_value);
}
int main() {
// attach a function executed each 1/FREQ s
tic.attach_us(tic_handler, 1000000.0/(float)FREQ);
while (1) {
// read an audio packet
audio.read((uint8_t *)buf);
available = true;
}
}
Samuel Mokrani