i2s_mic_example.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* pcm_record.c */
  2. #include "rtconfig.h"
  3. #if defined(BSP_USING_I2S)||defined(BSP_USING_SDIF)
  4. #include <rtthread.h>
  5. #include <rtdevice.h>
  6. #include <dfs_posix.h>
  7. #define RECORD_TIME_MS 5000
  8. #define RT_I2S_SAMPLERATE 8000
  9. #define RECORD_CHANNEL 2
  10. #define RECORD_CHUNK_SZ ((RT_I2S_SAMPLERATE * RECORD_CHANNEL * 2) * 20 / 1000)
  11. #define SOUND_DEVICE_NAME "I2S0" /* Audio 设备名称 */
  12. static rt_device_t mic_dev; /* Audio 设备句柄 */
  13. int pcm_record()
  14. {
  15. int fd = -1;
  16. uint8_t *buffer = NULL;
  17. int length, total_length = 0;
  18. fd = open("file.pcm", O_WRONLY | O_CREAT);
  19. if (fd < 0)
  20. {
  21. rt_kprintf("open file for recording failed!\n");
  22. return -1;
  23. }
  24. rt_kprintf("1\n");
  25. buffer = rt_malloc(RECORD_CHUNK_SZ);
  26. if (buffer == RT_NULL)
  27. goto __exit;
  28. rt_kprintf("2\n");
  29. mic_dev = rt_device_find(SOUND_DEVICE_NAME);
  30. if (mic_dev == RT_NULL)
  31. goto __exit;
  32. rt_kprintf("3\n");
  33. rt_device_open(mic_dev, RT_DEVICE_OFLAG_RDONLY);
  34. rt_kprintf("4\n");
  35. while (1)
  36. {
  37. rt_kprintf("6\n");
  38. length = rt_device_read(mic_dev, 0, buffer, RECORD_CHUNK_SZ);
  39. rt_kprintf("7\n");
  40. if (length)
  41. {
  42. write(fd, buffer, length);
  43. total_length += length;
  44. }
  45. if ((total_length / RECORD_CHUNK_SZ) > (RECORD_TIME_MS / 20))
  46. break;
  47. }
  48. close(fd);
  49. rt_device_close(mic_dev);
  50. __exit:
  51. if (fd >= 0)
  52. close(fd);
  53. if (buffer)
  54. rt_free(buffer);
  55. return 0;
  56. }
  57. MSH_CMD_EXPORT(pcm_record, record voice to a pcm file); // 修改命令描述
  58. #endif