videocapture_audio_combination.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <opencv2/core.hpp>
  2. #include <opencv2/videoio.hpp>
  3. #include <opencv2/highgui.hpp>
  4. #include <iostream>
  5. using namespace cv;
  6. using namespace std;
  7. int main(int argc, char** argv)
  8. {
  9. cv::CommandLineParser parser(argc, argv, "{@audio||}");
  10. string file = parser.get<string>("@audio");
  11. if (file.empty())
  12. {
  13. return 1;
  14. }
  15. Mat videoFrame;
  16. Mat audioFrame;
  17. vector<vector<Mat>> audioData;
  18. VideoCapture cap;
  19. vector<int> params { CAP_PROP_AUDIO_STREAM, 0,
  20. CAP_PROP_VIDEO_STREAM, 0,
  21. CAP_PROP_AUDIO_DATA_DEPTH, CV_16S };
  22. cap.open(file, CAP_MSMF, params);
  23. if (!cap.isOpened())
  24. {
  25. cerr << "ERROR! Can't to open file: " + file << endl;
  26. return -1;
  27. }
  28. const int audioBaseIndex = (int)cap.get(CAP_PROP_AUDIO_BASE_INDEX);
  29. const int numberOfChannels = (int)cap.get(CAP_PROP_AUDIO_TOTAL_CHANNELS);
  30. cout << "CAP_PROP_AUDIO_DATA_DEPTH: " << depthToString((int)cap.get(CAP_PROP_AUDIO_DATA_DEPTH)) << endl;
  31. cout << "CAP_PROP_AUDIO_SAMPLES_PER_SECOND: " << cap.get(CAP_PROP_AUDIO_SAMPLES_PER_SECOND) << endl;
  32. cout << "CAP_PROP_AUDIO_TOTAL_CHANNELS: " << cap.get(CAP_PROP_AUDIO_TOTAL_CHANNELS) << endl;
  33. cout << "CAP_PROP_AUDIO_TOTAL_STREAMS: " << cap.get(CAP_PROP_AUDIO_TOTAL_STREAMS) << endl;
  34. int numberOfSamples = 0;
  35. int numberOfFrames = 0;
  36. audioData.resize(numberOfChannels);
  37. for (;;)
  38. {
  39. if (cap.grab())
  40. {
  41. cap.retrieve(videoFrame);
  42. for (int nCh = 0; nCh < numberOfChannels; nCh++)
  43. {
  44. cap.retrieve(audioFrame, audioBaseIndex+nCh);
  45. if (!audioFrame.empty())
  46. audioData[nCh].push_back(audioFrame);
  47. numberOfSamples+=audioFrame.cols;
  48. }
  49. if (!videoFrame.empty())
  50. {
  51. numberOfFrames++;
  52. imshow("Live", videoFrame);
  53. if (waitKey(5) >= 0)
  54. break;
  55. }
  56. } else { break; }
  57. }
  58. cout << "Number of audio samples: " << numberOfSamples << endl
  59. << "Number of video frames: " << numberOfFrames << endl;
  60. return 0;
  61. }