RecordAudio.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include "RecordAudio.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <alsa/asoundlib.h>
  5. void record(int argc, char *argv[])
  6. {
  7. uint32_t sample_rate = 44100;
  8. uint32_t channels = 2;
  9. int i;
  10. int err;
  11. short buf[128];
  12. snd_pcm_t *capture_handle;
  13. snd_pcm_hw_params_t *hw_params;
  14. if ((err = snd_pcm_open (&capture_handle, argv[1], SND_PCM_STREAM_CAPTURE, 0)) < 0) {
  15. fprintf (stderr, "cannot open audio device %s (%s)\n",
  16. argv[1],
  17. snd_strerror (err));
  18. exit (1);
  19. }
  20. if ((err = snd_pcm_hw_params_malloc (&hw_params)) < 0) {
  21. fprintf (stderr, "cannot allocate hardware parameter structure (%s)\n",
  22. snd_strerror (err));
  23. exit (1);
  24. }
  25. if ((err = snd_pcm_hw_params_any (capture_handle, hw_params)) < 0) {
  26. fprintf (stderr, "cannot initialize hardware parameter structure (%s)\n",
  27. snd_strerror (err));
  28. exit (1);
  29. }
  30. if ((err = snd_pcm_hw_params_set_access (capture_handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0) {
  31. fprintf (stderr, "cannot set access type (%s)\n",
  32. snd_strerror (err));
  33. exit (1);
  34. }
  35. if ((err = snd_pcm_hw_params_set_format (capture_handle, hw_params, SND_PCM_FORMAT_S16_LE)) < 0) {
  36. fprintf (stderr, "cannot set sample format (%s)\n",
  37. snd_strerror (err));
  38. exit (1);
  39. }
  40. if ((err = snd_pcm_hw_params_set_rate_near (capture_handle, hw_params, &sample_rate, 0)) < 0) {
  41. fprintf (stderr, "cannot set sample rate (%s)\n",
  42. snd_strerror (err));
  43. exit (1);
  44. }
  45. if ((err = snd_pcm_hw_params_set_channels (capture_handle, hw_params, 2)) < 0) {
  46. fprintf (stderr, "cannot set channel count (%s)\n",
  47. snd_strerror (err));
  48. exit (1);
  49. }
  50. if ((err = snd_pcm_hw_params (capture_handle, hw_params)) < 0) {
  51. fprintf (stderr, "cannot set parameters (%s)\n",
  52. snd_strerror (err));
  53. exit (1);
  54. }
  55. snd_pcm_hw_params_free (hw_params);
  56. if ((err = snd_pcm_prepare (capture_handle)) < 0) {
  57. fprintf (stderr, "cannot prepare audio interface for use (%s)\n",
  58. snd_strerror (err));
  59. exit (1);
  60. }
  61. for (i = 0; i < 10; ++i) {
  62. if ((err = snd_pcm_readi (capture_handle, buf, 128)) != 128) {
  63. fprintf (stderr, "read from audio interface failed (%s)\n",
  64. snd_strerror (err));
  65. exit (1);
  66. }
  67. }
  68. snd_pcm_close (capture_handle);
  69. exit (0);
  70. }