ffmpeg中的采集麦克风的 API

发布时间 2023-09-07 15:33:51作者: 阿风小子

在FFmpeg中,可以使用libavdevice库来采集麦克风的音频。下面是一个简单示例:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdint.h>
  5.  
  6. #include <libavformat/avformat.h>
  7. #include <libavdevice/avdevice.h>
  8.  
  9. int main() {
  10. av_register_all();
  11. avdevice_register_all();
  12.  
  13. AVFormatContext *fmt_ctx = NULL;
  14. AVInputFormat *input_fmt = av_find_input_format("alsa"); // 音频设备的输入格式,如alsa、pulse等
  15. const char *dev_name = "default"; // 麦克风设备名称
  16.  
  17. // 打开音频设备
  18. if (avformat_open_input(&fmt_ctx, dev_name, input_fmt, NULL) != 0) {
  19. printf("无法打开音频设备\n");
  20. return -1;
  21. }
  22.  
  23. // 查找音频流信息
  24. if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
  25. printf("无法获取音频流信息\n");
  26. return -1;
  27. }
  28.  
  29. int audio_stream_idx = -1;
  30. // 寻找音频流索引
  31. for (int i = 0; i < fmt_ctx->nb_streams; i++) {
  32. if (fmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  33. audio_stream_idx = i;
  34. break;
  35. }
  36. }
  37.  
  38. if (audio_stream_idx == -1) {
  39. printf("找不到音频流\n");
  40. return -1;
  41. }
  42.  
  43. AVPacket packet;
  44.  
  45. while(av_read_frame(fmt_ctx, &packet) >= 0) {
  46. if (packet.stream_index == audio_stream_idx) {
  47. // 处理音频数据,可以在这里进行保存、处理等操作
  48. printf("收到音频数据\n");
  49. }
  50.  
  51. av_packet_unref(&packet);
  52. }
  53.  
  54. avformat_close_input(&fmt_ctx);
  55.  
  56. return 0;
  57. }

以上示例展示了使用FFmpeg采集麦克风的音频数据,你可以根据自己的需求进行进一步的处理和应用。需要注意的是,代码中的设备名称和输入格式可能需要根据实际情况进行修改。