• <Android音频>Android native层直接使用AudioFlinger播放pcm


    <Android音频>Android native层使用TrackPlayer播放pcm_王二の黄金时代的博客-CSDN博客

    <Android音频>Android native层直接使用AudioFlinger播放pcm_王二の黄金时代的博客-CSDN博客

    目录

    一:概述   一个c语言demo可执行程序,直接使用AudioFlinger 播放pcm.

    二:实现

    环境  ubuntu22.04 编译 aosp11 源码

    源码  main()

    结果


    一:概述

    这是一个c语言demo程序,android源码环境,编译得到 bin文件,push到设备上在shell环境运行,播放pcm数据。如果是app java开发,没有系统源码,就不建议往下看了。

    用于研究AudioFlinger源码,这是一个demo,在源码层面编译,直接获取AuduioFlinger服务,使用AudioFlinger的 public方法来播放一个demo.  原创,分析源码参考AudioTrack(native层)编写而来。 

    二:实现

    上demo:(github**暂未上传)

    环境

    • ubuntu22.04 编译 aosp11 源码,得到emulator 运行。 
    • 编译本demo 得到  out/target/product/generic_x86_64/system/bin/AFdemo 可执行程序,push到 emulator上运行。
    • 程序需要一个 48K,16bit, 双通道立体声的pcm 数据文件作为源,(可使用ffmpeg制作)

    源码

    main.cpp

    1. /*
    2. * author:cnaok 20220630
    3. * aosp 11 http://aospxref.com/android-11.0.0_r21/
    4. * 直接使用 AudioFlinger接口,播放pcm数据
    5. * 参照源码中 AudioTrack.cpp 和AudioFlinger的交互
    6. */
    7. #include <stdlib.h>
    8. #include <stdio.h>
    9. #include <iostream>
    10. #include <media/AudioSystem.h>
    11. #include <media/IAudioFlinger.h>
    12. #include <binder/IPCThreadState.h>
    13. #include <private/media/AudioTrackShared.h> // for audio_track_cblk_t
    14. using namespace android;
    15. // namespace android
    16. // {
    17. // 以每20ms的数据量,读一次文件
    18. #define WRITE_TIME_MS 20
    19. int track_demo()
    20. {
    21. // 初始化下源数据
    22. FILE *fp_in = fopen("yk_48000_2_16.pcm", "r");
    23. if (fp_in == NULL)
    24. {
    25. printf("[canok]erro to open file\n");
    26. return -1;
    27. }
    28. int chanles = 2; // static inline uint32_t audio_channel_count_from_out_mask(audio_channel_mask_t channel)
    29. int samplerate = 48000;
    30. int bits = 16;
    31. size_t mFrameSize = chanles * bits / 8; // channelCount * audio_bytes_per_sample(format);
    32. size_t mFrames = samplerate * WRITE_TIME_MS / 1000;
    33. int buf_size = mFrames * mFrameSize;
    34. void *buf = malloc(buf_size);
    35. if (buf == NULL)
    36. {
    37. printf("[canok]malloc erro\n");
    38. return -1;
    39. }
    40. // get_audio_flinger
    41. const sp<IAudioFlinger> &audioFlinger = AudioSystem::get_audio_flinger();
    42. if (audioFlinger == 0)
    43. {
    44. std::cout << "err to get audio_flinger" << std::endl;
    45. }
    46. IAudioFlinger::CreateTrackInput input;
    47. IAudioFlinger::CreateTrackOutput output;
    48. input.speed = 1.0;
    49. input.attr = AUDIO_ATTRIBUTES_INITIALIZER;
    50. input.frameCount = samplerate * WRITE_TIME_MS / 1000;
    51. input.config = AUDIO_CONFIG_INITIALIZER;
    52. input.config.sample_rate = samplerate;
    53. input.config.channel_mask = AUDIO_CHANNEL_OUT_STEREO; // 0x1u // system/media/audio/include/system/audio-base.h
    54. input.config.format = AUDIO_FORMAT_PCM_16_BIT; // AUDIO_FORMAT_PCM | AUDIO_FORMAT_PCM_16_BIT; // system/media/audio/include/system/audio-base.h
    55. // input.config.offload_info = mOffloadInfoCopy;
    56. input.clientInfo.clientTid = -1;
    57. input.sessionId = AUDIO_SESSION_ALLOCATE;
    58. input.clientInfo.clientPid = IPCThreadState::self()->getCallingPid();
    59. input.clientInfo.clientUid = IPCThreadState::self()->getCallingPid();
    60. status_t status = NO_ERROR;
    61. // 1.1 Audioflinger 请求创建mAudioTrack (Audioflinger内部会根据请求input的配置,从AudioPolicy获取合适的输出设备,打开)
    62. sp<IAudioTrack> mAudioTrack = audioFlinger->createTrack(input,
    63. output,
    64. &status);
    65. std::cout << "status:" << status << std::endl;
    66. std::cout << "creatTrack_ output:" << std::endl
    67. << " flags " << output.flags << std::endl
    68. << " frameCount " << output.frameCount << std::endl
    69. << " notificationFrameCount " << output.notificationFrameCount << std::endl
    70. << " selectedDeviceId " << output.selectedDeviceId << std::endl
    71. << " sessionId " << output.sessionId << std::endl
    72. << " afFrameCount " << output.afFrameCount << std::endl
    73. << " afSampleRate " << output.afSampleRate << std::endl
    74. << " afLatencyMs " << output.afLatencyMs << std::endl
    75. << " outputId " << output.outputId << std::endl
    76. << " portId " << output.portId << std::endl;
    77. if (mAudioTrack == nullptr)
    78. {
    79. printf("[canok]create audioTrack err\n");
    80. return -1;
    81. }
    82. // 1.2 start AudioTrack
    83. mAudioTrack->start();
    84. // 2.0 mCblkMemory 从AudioTrack获取mCblkMemory,用于后续 “共享内存” 操作对象
    85. sp<IMemory> mCblkMemory = mAudioTrack->getCblk();
    86. if (mCblkMemory == 0)
    87. {
    88. printf("[canok]%s: Could not get control block", __func__);
    89. }
    90. // 2.1 mCblk
    91. void *iMemPointer = mCblkMemory->unsecurePointer();
    92. if (iMemPointer == NULL)
    93. {
    94. printf("[canok]%s: Could not get control block pointer", __func__);
    95. status = NO_INIT;
    96. }
    97. audio_track_cblk_t *mCblk = static_cast<audio_track_cblk_t *>(iMemPointer);
    98. // 2.2 mProxy
    99. //创建一个 audio_track_cblk 的辅助操作对象,后续就通过这个对象,来往audioflinger放数据。
    100. sp<AudioTrackClientProxy> mProxy; // primary owner of the memory
    101. mProxy = new AudioTrackClientProxy(mCblk, mCblk + 1, output.frameCount, mFrameSize);
    102. // 3.0 从mProxy 获取buffer,填充buffer,释放buffer
    103. while (fread(buf, 1, buf_size, fp_in) > 0)
    104. {
    105. int count = mFrames;
    106. uint8_t *bufsrc = (uint8_t *)buf;
    107. while (count > 0)
    108. {
    109. printf("[canok]track: to obtainBuffer<<<<<<<<<[%s%d] count %d \n", __FUNCTION__, __LINE__, count);
    110. /* code */
    111. // 3.1获取一个 buffer
    112. Proxy::Buffer audioBuffer;
    113. audioBuffer.mFrameCount = count; //希望获取的frame 数量。
    114. const struct timespec *requested = &ClientProxy::kForever; // 无限超时
    115. status = mProxy->obtainBuffer(&audioBuffer, requested, NULL); // elapsed 为Null, elaped是一个输出参数,他会告诉你这个调用阻塞了多少时间,如果不需要这个数,给null
    116. // 获取的audioBuffer , mFrameCount中是实际获取到的帧数。
    117. std::cout << "obtainBufffer:" << std::endl
    118. << " status: " << status << std::endl
    119. << " mFrameCount: " << audioBuffer.mFrameCount << std::endl;
    120. if (status != NO_ERROR)
    121. {
    122. printf("[canok][%s%d] erro to obtainBuffer :%d \n", __FUNCTION__, __LINE__, status);
    123. }
    124. // 3.2 填充这个buffer
    125. size_t toWrite = audioBuffer.mFrameCount * mFrameSize;
    126. printf("[canok]track:[%s%d] toWrite:%zu srcPostion: %ld , srcLeaveSize: %ld \n", __FUNCTION__, __LINE__, toWrite, bufsrc - (uint8_t *)buf, buf_size - (bufsrc - (uint8_t *)buf));
    127. memcpy(audioBuffer.mRaw, bufsrc, toWrite);
    128. // 3.3 释放这个buffer
    129. mProxy->releaseBuffer(&audioBuffer);
    130. count -= audioBuffer.mFrameCount;
    131. bufsrc += toWrite;
    132. }
    133. }
    134. free(buf);
    135. fclose(fp_in);
    136. return 0;
    137. }
    138. int main(int argc, const char *argv[])
    139. {
    140. track_demo();
    141. return 0;
    142. }
    143. // }

    Android.bp

    1. cc_binary {
    2. name: "AFdemo",
    3. srcs: [
    4. "main.cpp",
    5. ],
    6. shared_libs: [
    7. "libaudioclient",
    8. "libaudioutils",
    9. "libutils",
    10. "libbinder",
    11. ],
    12. header_libs: [
    13. "libmedia_headers",
    14. ],
    15. include_dirs: [
    16. // "frameworks/av/media/libavextensions",
    17. "frameworks/av/media/libnbaio/include_mono/",
    18. ],
    19. cflags: [
    20. "-Wall",
    21. "-Werror",
    22. "-Wno-error=deprecated-declarations",
    23. "-Wno-unused-parameter",
    24. "-Wno-unused-variable",
    25. ],
    26. }

    结果

    可执行程序,push到设备上可以直接 shell环境运行,能播放声音。

    参照AudioTrack源码

  • 相关阅读:
    DVWA 靶场 Open HTTP Redirect 通关解析
    Java架构师面试必备题
    考试中心|学习资料|学习情况|纯净无广|在线组卷刷题
    【图像分割】实战篇(1)传统图像分割
    10. 对 componentWillReceiveProps 的理解?
    Spark常用算子
    Go 的 50 度灰: 新 Golang 开发者要注意的陷阱、技巧和常见错误
    【延期公告】2022年触觉与虚拟现实国际会议(ICHVR 2022)
    FL Studio21中文完整版升级下载
    Mindspore 控制流中存在原地更新操作类副作用算子时循环值不更新问题记录
  • 原文地址:https://blog.csdn.net/u012459903/article/details/125526729