Advertisement
Guest User

Untitled

a guest
May 21st, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.14 KB | None | 0 0
  1. // USBAudio speaker example
  2.  
  3. #include "mbed.h"
  4. #include "USBAudio.h"
  5.  
  6. // frequency: 48 kHz
  7. #define FREQ 48000
  8.  
  9. // 1 channel: mono
  10. #define NB_CHA 1
  11.  
  12. // 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
  13. #define AUDIO_LENGTH_PACKET 48 * 2 * 1
  14.  
  15. // USBAudio (we just use audio packets received, we don't send audio packets to the computer in this example)
  16. USBAudio audio(FREQ, NB_CHA, 8000, 1, 0x7180, 0x7500);
  17.  
  18. // speaker connected to the AnalogOut output. The audio stream received over USb will be sent to the speaker
  19. AnalogOut speaker(PA_4);
  20.  
  21. // ticker to send data to the speaker at the good frequency
  22. Ticker tic;
  23.  
  24. // buffer where will be store one audio packet (LENGTH_AUDIO_PACKET/2 because we are storing int16 and not uint8)
  25. int16_t buf[AUDIO_LENGTH_PACKET/2];
  26.  
  27. // show if an audio packet is available
  28. volatile bool available = false;
  29.  
  30. // index of the value which will be send to the speaker
  31. int index_buf = 0;
  32.  
  33. // previous value sent to the speaker
  34. uint16_t p_val = 0;
  35.  
  36. // function executed each 1/FREQ s
  37. void tic_handler() {
  38.     float speaker_value;
  39.  
  40.     if (available) {
  41.         //convert 2 bytes in float
  42.         speaker_value = (float)(buf[index_buf]);
  43.        
  44.         // speaker_value between 0 and 65535
  45.         speaker_value += 32768.0;
  46.  
  47.         // adjust according to current volume
  48.         speaker_value *= audio.getVolume();
  49.        
  50.         // as two bytes has been read, we move the index of two bytes
  51.         index_buf++;
  52.        
  53.         // if we have read all the buffer, no more data available
  54.         if (index_buf == AUDIO_LENGTH_PACKET/2) {
  55.             index_buf = 0;
  56.             available = false;
  57.         }
  58.     } else {
  59.         speaker_value = p_val;
  60.     }
  61.    
  62.     p_val = speaker_value;
  63.  
  64.     // send value to the speaker
  65.     speaker.write_u16((uint16_t)speaker_value);
  66. }
  67.  
  68. int main() {
  69.  
  70.     // attach a function executed each 1/FREQ s
  71.     tic.attach_us(tic_handler, 1000000.0/(float)FREQ);
  72.  
  73.     while (1) {
  74.         // read an audio packet
  75.         audio.read((uint8_t *)buf);
  76.         available = true;
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement