Browse
 
Tools
Rss Categories

audioStreamer.cpp

Reference Number: AA-01510 Views: 1792 0 Rating/ Voters

C++ Code

  1. #include "AudioStreamer.h"
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <io.h>

  5. //=============================================================================

  6. AudioStreamer::AudioStreamer(const char* filename) :
  7. increment_ms(300),
  8. audio_buffer_size(0),
  9. audio_buffer(NULL)
  10. {
  11. int audio_handle = _open(filename, _O_BINARY | _O_RDONLY);
  12. if (audio_handle <= 0)
  13. {
  14. printf("could not open audio file %s\n",filename);
  15. exit(-1);
  16. }

  17. audio_buffer_size = _lseek(audio_handle, 0L, SEEK_END);

  18. _lseek(audio_handle, 0L, SEEK_SET);
  19. audio_buffer = new char[audio_buffer_size];
  20. _read(audio_handle, audio_buffer, audio_buffer_size);
  21. _close(audio_handle);
  22. }

  23. //=============================================================================

  24. AudioStreamer::~AudioStreamer()
  25. {
  26. ThreadStop();
  27. delete[] audio_buffer;
  28. }

  29. //=============================================================================

  30. void AudioStreamer::StartStream(AudioStreamCB CB, void* UserData)
  31. {
  32. cb = CB;
  33. user_data = UserData;
  34. ThreadActivate();
  35. ThreadStart();
  36. printf("audio stream started\n");
  37. }

  38. //=============================================================================

  39. void AudioStreamer::StopStream()
  40. {
  41. ThreadStop();
  42. printf("audio stream stopped\n");
  43. }

  44. //=============================================================================

  45. void AudioStreamer::ThreadAction()
  46. {
  47. printf("audio thread working\n");
  48. int chunk_size;
  49. int end_chunk_size;
  50. char* current_pos = audio_buffer;
  51. bool feed_more = true;

  52. chunk_size = 8000*1*increment_ms/ 1000;
  53. end_chunk_size = chunk_size;
  54. end_buffer = new char[end_chunk_size];
  55. memset(end_buffer, 0, end_chunk_size);

  56. while (current_pos != audio_buffer + audio_buffer_size && feed_more && !IsThreadShuttingDown())
  57. {
  58. if (current_pos + chunk_size > audio_buffer + audio_buffer_size)
  59. {
  60. chunk_size = (audio_buffer + audio_buffer_size) - current_pos;
  61. }
  62. feed_more = cb(current_pos, chunk_size, user_data);
  63. current_pos += chunk_size;
  64. printf("sending audio\n");
  65. Sleep(increment_ms);
  66. }

  67. while (feed_more && !IsThreadShuttingDown())
  68. {
  69. feed_more = cb(end_buffer, end_chunk_size, user_data);
  70. Sleep(increment_ms);
  71. printf("sending dead air\n");
  72. }

  73. printf("audio thread told to shut down\n");
  74. delete[] end_buffer;
  75. }

  76. //=============================================================================