Guest User

How to record live audio into file from microphone with openAL (C++ code inside)

a guest
Feb 22nd, 2012
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <stdio.h>
  4. #include <windows.h>
  5. #include <al.h>
  6. #include <alc.h>
  7. using namespace std;
  8. int main()
  9. {
  10. ALCdevice *dev[2];
  11. ALCcontext *ctx;
  12. ALuint source, buffers[3];
  13. char data[5000];
  14. ALuint buf;
  15. ALint val;
  16.  
  17. dev[0] = alcOpenDevice(NULL);
  18. ctx = alcCreateContext(dev[0], NULL);
  19. alcMakeContextCurrent(ctx);
  20.  
  21. alGenSources(1, &source);
  22. alGenBuffers(3, buffers);
  23.  
  24. /* Setup some initial silent data to play out of the source */
  25. alBufferData(buffers[0], AL_FORMAT_MONO16, data, sizeof(data), 22050);
  26. alBufferData(buffers[1], AL_FORMAT_MONO16, data, sizeof(data), 22050);
  27. alBufferData(buffers[2], AL_FORMAT_MONO16, data, sizeof(data), 22050);
  28. alSourceQueueBuffers(source, 3, buffers);
  29.  
  30. /* If you don't need 3D spatialization, this should help processing time */
  31. alDistanceModel(AL_NONE);
  32.  
  33. dev[1] = alcCaptureOpenDevice(NULL, 22050, AL_FORMAT_MONO16, sizeof(data)/2);
  34.  
  35. /* Start playback and capture, and enter the audio loop */
  36. alSourcePlay(source);
  37. alcCaptureStart(dev[1]);
  38.  
  39. while(1)
  40. {
  41. /* Check if any queued buffers are finished */
  42. alGetSourcei(source, AL_BUFFERS_PROCESSED, &val);
  43. if(val <= 0)
  44. continue;
  45.  
  46. /* Check how much audio data has been captured (note that 'val' is the
  47. * number of frames, not bytes) */
  48. alcGetIntegerv(dev[1], ALC_CAPTURE_SAMPLES, 1, &val);
  49.  
  50. /* Read the captured audio */
  51. alcCaptureSamples(dev[1], data, val);
  52.  
  53. /* Pop the oldest finished buffer, fill it with the new capture data,
  54. then re-queue it to play on the source */
  55. alSourceUnqueueBuffers(source, 1, &buf);
  56. alBufferData(buf, AL_FORMAT_MONO16, data, val*2 /* bytes here, not
  57. frames */, 22050);
  58. alSourceQueueBuffers(source, 1, &buf);
  59.  
  60. /* Make sure the source is still playing */
  61. alGetSourcei(source, AL_SOURCE_STATE, &val);
  62.  
  63. if(val != AL_PLAYING)
  64. {
  65.  
  66. alSourcePlay(source);
  67. }
  68. }
  69.  
  70. /* Shutdown and cleanup */
  71. alcCaptureStop(dev[1]);
  72. alcCaptureCloseDevice(dev[1]);
  73.  
  74. alSourceStop(source);
  75. alDeleteSources(1, &source);
  76. alDeleteBuffers(3, buffers);
  77.  
  78. alcMakeContextCurrent(NULL);
  79. alcDestroyContext(ctx);
  80. alcCloseDevice(dev[0]);
  81.  
  82. return 0;
  83. }
Add Comment
Please, Sign In to add comment