视频上很容易就可以做到撒,一般的视频格式都是每秒固定的帧数,按比例跳帧就可以了撒。音频上其实也可以用这种方式来直接删除一些周期,因为电脑里的音频也是数字化离散化地储存的。但是为了使声音不失真,应该都用了稍复杂一点的算法的,比方说把相邻时钟周期内的声音电平信号取平均,或者用高斯平均值代替原信号,再精细点可以自适应地在音调信号比较丰富的地方设置比较高的权重来尽量少压缩保持音色,总之有很多种方法都可以做到啦。因为没有关注过这个,所以并不知道在软件里具体是怎么实现的,但是数字信号的缩放、滤波这些算法应该都差不多是这么做的,音频的加速也不像是需要使用更复杂的非线性自适应滤波的样子。


作者:匿名用户
链接:https://www.zhihu.com/question/35659196/answer/83096015
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

音频倍速(变速不变调)的实现


http://blog.csdn.net/abcsunl/article/details/77196788

背景:

        项目需要,开发一款自己的安卓端播放器SDK,其中需要有一个视频倍速播放的功能。需要实现的效果是变速不变调。项目基于FFMpeg和WebRtc,通过FFMpeg从网络读取视频流,经过解封装、解复用分离成音频数据包和视频数据包。并分别对音视频数据包进行解码,解码完成之后的音频PCM(44100Hz,16bit,MONO)数据通过WebRtc提供的接口抛给AudioTrack,视频YUV420数据抛给WebRtc通过VideoRenderer进行渲染。


弯路:

        1.一下子给播放设备(通过WebRtc注册的Audio Playout Device)喂两倍的数据:可以实现两倍速不变调,原理未知(WebRtc内部实现机制),但是有刺啦刺啦的噪音,推测是基音周期的问题,会产生基音断裂,定位困难,靠自己实现困难,放弃了该方案。

        2.将解码的速率变成22050Hz,通过WebRtc播放(播放器初始化为44100Hz)可以实现两倍,但是会变调,放弃。

        3.丢帧,每隔一帧丢一帧,可以实现音频倍速,但是也会有刺啦刺啦的噪音(基音断裂的问题),而且声音会产生断续,体验十分差,放弃。


寻找新的解决方法:

        靠自己解决这个基音周期的问题需要算法和实现,不现实,只能通过调用现有的库进行处理。经过调研,发现有两个库支持倍速处理,一个是SoundTouch,另一个是Sonic。由于谷歌官方提供了一个ExoPlayer播放器,其中应用的方法是Sonic,并且网上有对两个库进行比较的文章,Sonic的效果要略好于SoundTouch,于是决定用Sonic库。

       Sonic库有两种实现,一种是Java实现的Sonic.java,一种是C实现的Sonic-ndk,因为我们要和FFMpeg共同处理,所以选用了ndk库。


解决:

         先把Sonic的源码贴在这儿,里面有我写的部分简单的注释,可能有不对的地方,如果有发现的还望批评指正。

        头文件:

[cpp]  view plain  copy
  1. /* Sonic library 
  2.    Copyright 2010 
  3.    Bill Cox 
  4.    This file is part of the Sonic Library. 
  5.  
  6.    This file is licensed under the Apache 2.0 license, and also placed into the public domain. 
  7.    Use it either way, at your option. 
  8. */  
  9.   
  10. /* 
  11. The Sonic Library implements a new algorithm invented by Bill Cox for the 
  12. specific purpose of speeding up speech by high factors at high quality.  It 
  13. generates smooth speech at speed up factors as high as 6X, possibly more.  It is 
  14. also capable of slowing down speech, and generates high quality results 
  15. regardless of the speed up or slow down factor.  For speeding up speech by 2X or 
  16. more, the following equation is used: 
  17.  
  18.     newSamples = period/(speed - 1.0) 
  19.     scale = 1.0/newSamples; 
  20.  
  21. where period is the current pitch period, determined using AMDF or any other 
  22. pitch estimator, and speed is the speedup factor.  If the current position in 
  23. the input stream is pointed to by "samples", and the current output stream 
  24. position is pointed to by "out", then newSamples number of samples can be 
  25. generated with: 
  26.  
  27.     out[t] = (samples[t]*(newSamples - t) + samples[t + period]*t)/newSamples; 
  28.  
  29. where t = 0 to newSamples - 1. 
  30.  
  31. For speed factors < 2X, the PICOLA algorithm is used.  The above 
  32. algorithm is first used to double the speed of one pitch period.  Then, enough 
  33. input is directly copied from the input to the output to achieve the desired 
  34. speed up factor, where 1.0 < speed < 2.0.  The amount of data copied is derived: 
  35.  
  36.     speed = (2*period + length)/(period + length) 
  37.     speed*length + speed*period = 2*period + length 
  38.     length(speed - 1) = 2*period - speed*period 
  39.     length = period*(2 - speed)/(speed - 1) 
  40.  
  41. For slowing down speech where 0.5 < speed < 1.0, a pitch period is inserted into 
  42. the output twice, and length of input is copied from the input to the output 
  43. until the output desired speed is reached.  The length of data copied is: 
  44.  
  45.     length = period*(speed - 0.5)/(1 - speed) 
  46.  
  47. For slow down factors below 0.5, no data is copied, and an algorithm 
  48. similar to high speed factors is used. 
  49. */  
  50.   
  51. #ifdef  __cplusplus  
  52. extern "C" {  
  53. #endif  
  54.   
  55. /* Uncomment this to use sin-wav based overlap add which in theory can improve 
  56.    sound quality slightly, at the expense of lots of floating point math. */  
  57. /* #define SONIC_USE_SIN */  
  58.   
  59. /* This specifies the range of voice pitches we try to match. 
  60.    Note that if we go lower than 65, we could overflow in findPitchInRange */  
  61. #define SONIC_MIN_PITCH 65  
  62. #define SONIC_MAX_PITCH 400  
  63.   
  64. /* These are used to down-sample some inputs to improve speed */  
  65. #define SONIC_AMDF_FREQ 4000  
  66.   
  67. struct sonicStreamStruct;  
  68. typedef struct sonicStreamStruct *sonicStream;  
  69.   
  70. /* For all of the following functions, numChannels is multiplied by numSamples 
  71.    to determine the actual number of values read or returned. */  
  72.   
  73. /* Create a sonic stream.  Return NULL only if we are out of memory and cannot 
  74.   allocate the stream. Set numChannels to 1 for mono, and 2 for stereo. */  
  75. // 创建一个音频流,如果内存溢出不能创建流会返回NULL,numCHannels表示声道的个数,1为单声道,2为双声道  
  76. sonicStream sonicCreateStream(int sampleRate, int numChannels);  
  77. /* Destroy the sonic stream. */  
  78. // 销毁一个音频流  
  79. void sonicDestroyStream(sonicStream stream);  
  80. /* Use this to write floating point data to be speed up or down into the stream. 
  81.    Values must be between -1 and 1.  Return 0 if memory realloc failed, otherwise 1 */  
  82. //  
  83. int sonicWriteFloatToStream(sonicStream stream, float *samples, int numSamples);  
  84. /* Use this to write 16-bit data to be speed up or down into the stream. 
  85.    Return 0 if memory realloc failed, otherwise 1 */  
  86. int sonicWriteShortToStream(sonicStream stream, short *samples, int numSamples);  
  87. /* Use this to write 8-bit unsigned data to be speed up or down into the stream. 
  88.    Return 0 if memory realloc failed, otherwise 1 */  
  89. int sonicWriteUnsignedCharToStream(sonicStream stream, unsigned char *samples, int numSamples);  
  90. /* Use this to read floating point data out of the stream.  Sometimes no data 
  91.    will be available, and zero is returned, which is not an error condition. */  
  92. int sonicReadFloatFromStream(sonicStream stream, float *samples, int maxSamples);  
  93. /* Use this to read 16-bit data out of the stream.  Sometimes no data will 
  94.    be available, and zero is returned, which is not an error condition. */  
  95. int sonicReadShortFromStream(sonicStream stream, short *samples, int maxSamples);  
  96. /* Use this to read 8-bit unsigned data out of the stream.  Sometimes no data will 
  97.    be available, and zero is returned, which is not an error condition. */  
  98. int sonicReadUnsignedCharFromStream(sonicStream stream, unsigned char *samples, int maxSamples);  
  99. /* Force the sonic stream to generate output using whatever data it currently 
  100.    has.  No extra delay will be added to the output, but flushing in the middle of 
  101.    words could introduce distortion. */  
  102. // 立即强制刷新流  
  103. int sonicFlushStream(sonicStream stream);  
  104. /* Return the number of samples in the output buffer */  
  105. // 返回输出缓冲中的采样点数目  
  106. int sonicSamplesAvailable(sonicStream stream);  
  107. /* Get the speed of the stream. */  
  108. // 得到音频流的速度  
  109. float sonicGetSpeed(sonicStream stream);  
  110. /* Set the speed of the stream. */  
  111. // 设置音频流的速度  
  112. void sonicSetSpeed(sonicStream stream, float speed);  
  113. /* Get the pitch of the stream. */  
  114. float sonicGetPitch(sonicStream stream);  
  115. /* Set the pitch of the stream. */  
  116. void sonicSetPitch(sonicStream stream, float pitch);  
  117. /* Get the rate of the stream. */  
  118. float sonicGetRate(sonicStream stream);  
  119. /* Set the rate of the stream. */  
  120. void sonicSetRate(sonicStream stream, float rate);  
  121. /* Get the scaling factor of the stream. */  
  122. float sonicGetVolume(sonicStream stream);  
  123. /* Set the scaling factor of the stream. */  
  124. void sonicSetVolume(sonicStream stream, float volume);  
  125. /* Get the chord pitch setting. */  
  126. int sonicGetChordPitch(sonicStream stream);  
  127. /* Set chord pitch mode on or off.  Default is off.  See the documentation 
  128.    page for a description of this feature. */  
  129. void sonicSetChordPitch(sonicStream stream, int useChordPitch);  
  130. /* Get the quality setting. */  
  131. // 得到音频流的质量  
  132. int sonicGetQuality(sonicStream stream);  
  133. /* Set the "quality".  Default 0 is virtually as good as 1, but very much faster. */  
  134. // 设置音频流的质量,默认的0的质量几乎和1的一样好,但是更快  
  135. void sonicSetQuality(sonicStream stream, int quality);  
  136. /* Get the sample rate of the stream. */  
  137. // 得到音频流的采样率  
  138. int sonicGetSampleRate(sonicStream stream);  
  139. /* Set the sample rate of the stream.  This will drop any samples that have not been read. */  
  140. // 设置音频流的采样率  
  141. void sonicSetSampleRate(sonicStream stream, int sampleRate);  
  142. /* Get the number of channels. */  
  143. // 得到音频的声道数  
  144. int sonicGetNumChannels(sonicStream stream);  
  145. /* Set the number of channels.  This will drop any samples that have not been read. */  
  146. // 设置音频流的声道数  
  147. void sonicSetNumChannels(sonicStream stream, int numChannels);  
  148. /* This is a non-stream oriented interface to just change the speed of a sound 
  149.    sample.  It works in-place on the sample array, so there must be at least 
  150.    speed*numSamples available space in the array. Returns the new number of samples. */  
  151. // 这是一个非面向流的借口,只是改变声音采样的速率。它工作在采样数组内部,  
  152. //所以在数组内至少要有speed*numSampes大小的空间。返回值是新的采样点的数目  
  153.   
  154. int sonicChangeFloatSpeed(float *samples, int numSamples, float speed, float pitch,  
  155.     float rate, float volume, int useChordPitch, int sampleRate, int numChannels);  
  156. /* This is a non-stream oriented interface to just change the speed of a sound 
  157.    sample.  It works in-place on the sample array, so there must be at least 
  158.    speed*numSamples available space in the array. Returns the new number of samples. */  
  159. int sonicChangeShortSpeed(short *samples, int numSamples, float speed, float pitch,  
  160.     float rate, float volume, int useChordPitch, int sampleRate, int numChannels);  
  161.   
  162. #ifdef  __cplusplus  
  163. }  
  164. #endif  
        源文件:

[cpp]  view plain  copy
  1. /* Sonic library 
  2.    Copyright 2010 
  3.    Bill Cox 
  4.    This file is part of the Sonic Library. 
  5.  
  6.    This file is licensed under the Apache 2.0 license, and also placed into the public domain. 
  7.    Use it either way, at your option. 
  8. */  
  9.   
  10. #include <stdio.h>  
  11. #include <stdlib.h>  
  12. #include <string.h>  
  13. #include <stdarg.h>  
  14. #include <limits.h>  
  15. #include <math.h>  
  16. #include "sonic.h"  
  17. //#include "webrtc/base/logging.h"  
  18. #ifndef M_PI  
  19. #define M_PI 3.14159265358979323846  
  20. #endif  
  21.   
  22. /* 
  23.     The following code was used to generate the following sinc lookup table. 
  24.  
  25.     #include <math.h> 
  26.     #include <limits.h> 
  27.     #include <stdio.h> 
  28.      
  29.     double findHannWeight(int N, double x) { 
  30.         return 0.5*(1.0 - cos(2*M_PI*x/N)); 
  31.     } 
  32.      
  33.     double findSincCoefficient(int N, double x) { 
  34.         double hannWindowWeight = findHannWeight(N, x); 
  35.         double sincWeight; 
  36.      
  37.         x -= N/2.0; 
  38.         if (x > 1e-9 || x < -1e-9) { 
  39.             sincWeight = sin(M_PI*x)/(M_PI*x); 
  40.         } else { 
  41.             sincWeight = 1.0; 
  42.         } 
  43.         return hannWindowWeight*sincWeight; 
  44.     } 
  45.      
  46.     int main() { 
  47.         double x; 
  48.         int i; 
  49.         int N = 12; 
  50.      
  51.         for (i = 0, x = 0.0; x <= N; x += 0.02, i++) { 
  52.             printf("%u %d\n", i, (int)(SHRT_MAX*findSincCoefficient(N, x))); 
  53.         } 
  54.         return 0; 
  55.     } 
  56. */  
  57.   
  58. /* The number of points to use in the sinc FIR filter for resampling. */  
  59. #define SINC_FILTER_POINTS 12 /* I am not able to hear improvement with higher N. */  
  60. #define SINC_TABLE_SIZE 601  
  61.   
  62. /* Lookup table for windowed sinc function of SINC_FILTER_POINTS points. */  
  63. static short sincTable[SINC_TABLE_SIZE] = {  
  64.     0, 0, 0, 0, 0, 0, 0, -1, -1, -2, -2, -3, -4, -6, -7, -9, -10, -12, -14,  
  65.     -17, -19, -21, -24, -26, -29, -32, -34, -37, -40, -42, -44, -47, -48, -50,  
  66.     -51, -52, -53, -53, -53, -52, -50, -48, -46, -43, -39, -34, -29, -22, -16,  
  67.     -8, 0, 9, 19, 29, 41, 53, 65, 79, 92, 107, 121, 137, 152, 168, 184, 200,  
  68.     215, 231, 247, 262, 276, 291, 304, 317, 328, 339, 348, 357, 363, 369, 372,  
  69.     374, 375, 373, 369, 363, 355, 345, 332, 318, 300, 281, 259, 234, 208, 178,  
  70.     147, 113, 77, 39, 0, -41, -85, -130, -177, -225, -274, -324, -375, -426,  
  71.     -478, -530, -581, -632, -682, -731, -779, -825, -870, -912, -951, -989,  
  72.     -1023, -1053, -1080, -1104, -1123, -1138, -1149, -1154, -1155, -1151,  
  73.     -1141, -1125, -1105, -1078, -1046, -1007, -963, -913, -857, -796, -728,  
  74.     -655, -576, -492, -403, -309, -210, -107, 0, 111, 225, 342, 462, 584, 708,  
  75.     833, 958, 1084, 1209, 1333, 1455, 1575, 1693, 1807, 1916, 2022, 2122, 2216,  
  76.     2304, 2384, 2457, 2522, 2579, 2625, 2663, 2689, 2706, 2711, 2705, 2687,  
  77.     2657, 2614, 2559, 2491, 2411, 2317, 2211, 2092, 1960, 1815, 1658, 1489,  
  78.     1308, 1115, 912, 698, 474, 241, 0, -249, -506, -769, -1037, -1310, -1586,  
  79.     -1864, -2144, -2424, -2703, -2980, -3254, -3523, -3787, -4043, -4291,  
  80.     -4529, -4757, -4972, -5174, -5360, -5531, -5685, -5819, -5935, -6029,  
  81.     -6101, -6150, -6175, -6175, -6149, -6096, -6015, -5905, -5767, -5599,  
  82.     -5401, -5172, -4912, -4621, -4298, -3944, -3558, -3141, -2693, -2214,  
  83.     -1705, -1166, -597, 0, 625, 1277, 1955, 2658, 3386, 4135, 4906, 5697, 6506,  
  84.     7332, 8173, 9027, 9893, 10769, 11654, 12544, 13439, 14335, 15232, 16128,  
  85.     17019, 17904, 18782, 19649, 20504, 21345, 22170, 22977, 23763, 24527,  
  86.     25268, 25982, 26669, 27327, 27953, 28547, 29107, 29632, 30119, 30569,  
  87.     30979, 31349, 31678, 31964, 32208, 32408, 32565, 32677, 32744, 32767,  
  88.     32744, 32677, 32565, 32408, 32208, 31964, 31678, 31349, 30979, 30569,  
  89.     30119, 29632, 29107, 28547, 27953, 27327, 26669, 25982, 25268, 24527,  
  90.     23763, 22977, 22170, 21345, 20504, 19649, 18782, 17904, 17019, 16128,  
  91.     15232, 14335, 13439, 12544, 11654, 10769, 9893, 9027, 8173, 7332, 6506,  
  92.     5697, 4906, 4135, 3386, 2658, 1955, 1277, 625, 0, -597, -1166, -1705,  
  93.     -2214, -2693, -3141, -3558, -3944, -4298, -4621, -4912, -5172, -5401,  
  94.     -5599, -5767, -5905, -6015, -6096, -6149, -6175, -6175, -6150, -6101,  
  95.     -6029, -5935, -5819, -5685, -5531, -5360, -5174, -4972, -4757, -4529,  
  96.     -4291, -4043, -3787, -3523, -3254, -2980, -2703, -2424, -2144, -1864,  
  97.     -1586, -1310, -1037, -769, -506, -249, 0, 241, 474, 698, 912, 1115, 1308,  
  98.     1489, 1658, 1815, 1960, 2092, 2211, 2317, 2411, 2491, 2559, 2614, 2657,  
  99.     2687, 2705, 2711, 2706, 2689, 2663, 2625, 2579, 2522, 2457, 2384, 2304,  
  100.     2216, 2122, 2022, 1916, 1807, 1693, 1575, 1455, 1333, 1209, 1084, 958, 833,  
  101.     708, 584, 462, 342, 225, 111, 0, -107, -210, -309, -403, -492, -576, -655,  
  102.     -728, -796, -857, -913, -963, -1007, -1046, -1078, -1105, -1125, -1141,  
  103.     -1151, -1155, -1154, -1149, -1138, -1123, -1104, -1080, -1053, -1023, -989,  
  104.     -951, -912, -870, -825, -779, -731, -682, -632, -581, -530, -478, -426,  
  105.     -375, -324, -274, -225, -177, -130, -85, -41, 0, 39, 77, 113, 147, 178,  
  106.     208, 234, 259, 281, 300, 318, 332, 345, 355, 363, 369, 373, 375, 374, 372,  
  107.     369, 363, 357, 348, 339, 328, 317, 304, 291, 276, 262, 247, 231, 215, 200,  
  108.     184, 168, 152, 137, 121, 107, 92, 79, 65, 53, 41, 29, 19, 9, 0, -8, -16,  
  109.     -22, -29, -34, -39, -43, -46, -48, -50, -52, -53, -53, -53, -52, -51, -50,  
  110.     -48, -47, -44, -42, -40, -37, -34, -32, -29, -26, -24, -21, -19, -17, -14,  
  111.     -12, -10, -9, -7, -6, -4, -3, -2, -2, -1, -1, 0, 0, 0, 0, 0, 0, 0  
  112. };  
  113.   
  114. struct sonicStreamStruct {  
  115.     short *inputBuffer;  
  116.     short *outputBuffer;  
  117.     short *pitchBuffer;  
  118.     short *downSampleBuffer;  
  119.     float speed;  
  120.     float volume;  
  121.     float pitch;  
  122.     float rate;  
  123.     int oldRatePosition;  
  124.     int newRatePosition;  
  125.     int useChordPitch;  
  126.     int quality;  
  127.     int numChannels;  
  128.     int inputBufferSize;  
  129.     int pitchBufferSize;  
  130.     int outputBufferSize;  
  131.     int numInputSamples;  
  132.     int numOutputSamples;  
  133.     int numPitchSamples;  
  134.     int minPeriod;  
  135.     int maxPeriod;  
  136.     int maxRequired;  
  137.     int remainingInputToCopy;  
  138.     int sampleRate;  
  139.     int prevPeriod;  
  140.     int prevMinDiff;  
  141.     float avePower;  
  142. };  
  143.   
  144. /* Scale the samples by the factor. */  
  145. // 改变音量  
  146. static void scaleSamples(  
  147.     short *samples,  
  148.     int numSamples,  
  149.     float volume)  
  150. {  
  151.     int fixedPointVolume = volume*4096.0f;  
  152.     int value;  
  153.   
  154.     while(numSamples--) {  
  155.         value = (*samples*fixedPointVolume) >> 12;  
  156.         if(value > 32767) {  
  157.             value = 32767;  
  158.         } else if(value < -32767) {  
  159.             value = -32767;  
  160.         }  
  161.         *samples++ = value;  
  162.     }  
  163. }  
  164.   
  165. /* Get the speed of the stream. */  
  166. // 得到流的速度  
  167. float sonicGetSpeed(  
  168.     sonicStream stream)  
  169. {  
  170.     return stream->speed;  
  171. }  
  172.   
  173. /* Set the speed of the stream. */  
  174. // 设置流的速度  
  175. void sonicSetSpeed(  
  176.     sonicStream stream,  
  177.     float speed)  
  178. {  
  179.     stream->speed = speed;  
  180. }  
  181.   
  182. /* Get the pitch of the stream. */  
  183. // 得到流的音调  
  184. float sonicGetPitch(  
  185.     sonicStream stream)  
  186. {  
  187.     return stream->pitch;  
  188. }  
  189.   
  190. /* Set the pitch of the stream. */  
  191. // 设置流的音调  
  192. void sonicSetPitch(  
  193.     sonicStream stream,  
  194.     float pitch)  
  195. {  
  196.     stream->pitch = pitch;  
  197. }  
  198.   
  199. /* Get the rate of the stream. */  
  200. // 得到流的速率  
  201. float sonicGetRate(  
  202.     sonicStream stream)  
  203. {  
  204.     return stream->rate;  
  205. }  
  206.   
  207. /* Set the playback rate of the stream. This scales pitch and speed at the same time. */  
  208. // 设置回放流的速率,同时也重设pitch和speed  
  209. void sonicSetRate(  
  210.     sonicStream stream,  
  211.     float rate)  
  212. {  
  213.     stream->rate = rate;  
  214.   
  215.     stream->oldRatePosition = 0;  
  216.     stream->newRatePosition = 0;  
  217. }  
  218.   
  219. /* Get the vocal chord pitch setting. */  
  220. //  
  221. int sonicGetChordPitch(  
  222.     sonicStream stream)  
  223. {  
  224.     return stream->useChordPitch;  
  225. }  
  226.   
  227. /* Set the vocal chord mode for pitch computation.  Default is off. */  
  228. void sonicSetChordPitch(  
  229.     sonicStream stream,  
  230.     int useChordPitch)  
  231. {  
  232.     stream->useChordPitch = useChordPitch;  
  233. }  
  234.   
  235. /* Get the quality setting. */  
  236. int sonicGetQuality(  
  237.     sonicStream stream)  
  238. {  
  239.     return stream->quality;  
  240. }  
  241.   
  242. /* Set the "quality".  Default 0 is virtually as good as 1, but very much faster. */  
  243. void sonicSetQuality(  
  244.     sonicStream stream,  
  245.     int quality)  
  246. {  
  247.     stream->quality = quality;  
  248. }  
  249.   
  250. /* Get the scaling factor of the stream. */  
  251. float sonicGetVolume(  
  252.     sonicStream stream)  
  253. {  
  254.     return stream->volume;  
  255. }  
  256.   
  257. /* Set the scaling factor of the stream. */  
  258. // 设置流的音量  
  259. void sonicSetVolume(  
  260.     sonicStream stream,  
  261.     float volume)  
  262. {  
  263.     stream->volume = volume;  
  264. }  
  265.   
  266. /* Free stream buffers. */  
  267. // 释放流内的缓冲区  
  268. static void freeStreamBuffers(  
  269.     sonicStream stream)  
  270. {  
  271.     if(stream->inputBuffer != NULL) {  
  272.         free(stream->inputBuffer);  
  273.     }  
  274.     if(stream->outputBuffer != NULL) {  
  275.         free(stream->outputBuffer);  
  276.     }  
  277.     if(stream->pitchBuffer != NULL) {  
  278.         free(stream->pitchBuffer);  
  279.     }  
  280.     if(stream->downSampleBuffer != NULL) {  
  281.         free(stream->downSampleBuffer);  
  282.     }  
  283. }  
  284.   
  285. /* Destroy the sonic stream. */  
  286. // 销毁流  
  287. void sonicDestroyStream(  
  288.     sonicStream stream)  
  289. {  
  290.     freeStreamBuffers(stream);  
  291.     free(stream);  
  292. }  
  293.   
  294. /* Allocate stream buffers. */  
  295. /** 
  296.  * 开辟流的数据缓存空间 
  297.  * stream 流 
  298.  * sampleRate 采样率 
  299.  * numChnnels 声道数 
  300.  */  
  301. static int allocateStreamBuffers(  
  302.     sonicStream stream,  
  303.     int sampleRate,  
  304.     int numChannels)  
  305. {   // 最小的pitch周期 44100/400 = 110  
  306.     int minPeriod = sampleRate/SONIC_MAX_PITCH;  
  307.     // 最大的pitch周期 44100/65 = 678 个采样点  
  308.     int maxPeriod = sampleRate/SONIC_MIN_PITCH;  
  309.     // 最大 1356  
  310.     int maxRequired = 2*maxPeriod;   
  311.     // 输入缓冲区的大小 = maxRequired  
  312.     stream->inputBufferSize = maxRequired;  
  313.     // 为inputBuffer开辟空间并初始化为0  
  314.     stream->inputBuffer = (short *)calloc(maxRequired, sizeof(short)*numChannels);  
  315.     // 如果开辟失败返回0  
  316.     if(stream->inputBuffer == NULL) {  
  317.         sonicDestroyStream(stream);  
  318.         return 0;  
  319.     }  
  320.     // 输出缓冲区的大小= maxRequired  
  321.     stream->outputBufferSize = maxRequired;  
  322.     // 为oututBUffer开辟空间  
  323.     stream->outputBuffer = (short *)calloc(maxRequired, sizeof(short)*numChannels);  
  324.     if(stream->outputBuffer == NULL) {  
  325.         sonicDestroyStream(stream);  
  326.         return 0;  
  327.     }  
  328.     // 为pitchBuffer开辟空间  
  329.     stream->pitchBufferSize = maxRequired;  
  330.     stream->pitchBuffer = (short *)calloc(maxRequired, sizeof(short)*numChannels);  
  331.     if(stream->pitchBuffer == NULL) {  
  332.         sonicDestroyStream(stream);  
  333.         return 0;  
  334.     }  
  335.     // 为downSampleBuffer(降采样)开辟空间  
  336.     stream->downSampleBuffer = (short *)calloc(maxRequired, sizeof(short));  
  337.     if(stream->downSampleBuffer == NULL) {  
  338.         sonicDestroyStream(stream);  
  339.         return 0;  
  340.     }  
  341.     // 初始化各项参数  
  342.     stream->sampleRate = sampleRate;  
  343.     stream->numChannels = numChannels;  
  344.     stream->oldRatePosition = 0;  
  345.     stream->newRatePosition = 0;  
  346.     stream->minPeriod = minPeriod;  
  347.     stream->maxPeriod = maxPeriod;  
  348.     stream->maxRequired = maxRequired;  
  349.     stream->prevPeriod = 0;  
  350.     return 1;  
  351. }  
  352.   
  353. /* Create a sonic stream.  Return NULL only if we are out of memory and cannot 
  354.    allocate the stream. */  
  355. // 创建一个音频流  
  356. sonicStream sonicCreateStream(  
  357.     int sampleRate,  
  358.     int numChannels)  
  359. {  
  360.     // 开辟一个sonicStreamStruct大小的空间  
  361.     sonicStream stream = (sonicStream)calloc(1, sizeof(struct sonicStreamStruct));  
  362.     // 如果流为空,证明开辟失败  
  363.     if(stream == NULL) {  
  364.         return NULL;  
  365.     }  
  366.     if(!allocateStreamBuffers(stream, sampleRate, numChannels)) {  
  367.         return NULL;  
  368.     }  
  369.     // 初始化各项参数  
  370.     stream->speed = 1.0f;  
  371.     stream->pitch = 1.0f;  
  372.     stream->volume = 1.0f;  
  373.     stream->rate = 1.0f;  
  374.     stream->oldRatePosition = 0;  
  375.     stream->newRatePosition = 0;  
  376.     stream->useChordPitch = 0;  
  377.     stream->quality = 0;  
  378.     stream->avePower = 50.0f;  
  379.     return stream;  
  380. }  
  381.   
  382. /* Get the sample rate of the stream. */  
  383. // 取得流的采样率  
  384. int sonicGetSampleRate(  
  385.     sonicStream stream)  
  386. {  
  387.     return stream->sampleRate;  
  388. }  
  389.   
  390. /* Set the sample rate of the stream.  This will cause samples buffered in the stream to 
  391.    be lost. */  
  392. // 设置流的采样率,可能使流中的已经缓冲的数据丢失  
  393. void sonicSetSampleRate(  
  394.     sonicStream stream,  
  395.     int sampleRate)  
  396. {  
  397.     freeStreamBuffers(stream);  
  398.     allocateStreamBuffers(stream, sampleRate, stream->numChannels);  
  399. }  
  400.   
  401. /* Get the number of channels. */  
  402. // 取得流的声道的数量  
  403. int sonicGetNumChannels(  
  404.     sonicStream stream)  
  405. {  
  406.     return stream->numChannels;  
  407. }  
  408.   
  409. /* Set the num channels of the stream.  This will cause samples buffered in the stream to 
  410.    be lost. */  
  411. // 设置流的声道数量,可能造成流中已缓存的额数据的丢失  
  412. void sonicSetNumChannels(  
  413.     sonicStream stream,  
  414.     int numChannels)  
  415. {  
  416.     freeStreamBuffers(stream);  
  417.     allocateStreamBuffers(stream, stream->sampleRate, numChannels);  
  418. }  
  419.   
  420. /* Enlarge the output buffer if needed. */  
  421. // 根据需要扩大输出缓冲区  
  422. static int enlargeOutputBufferIfNeeded(  
  423.     sonicStream stream,  
  424.     int numSamples)  
  425. {  
  426.     if(stream->numOutputSamples + numSamples > stream->outputBufferSize) {  
  427.         stream->outputBufferSize += (stream->outputBufferSize >> 1) + numSamples;  
  428.         stream->outputBuffer = (short *)realloc(stream->outputBuffer,  
  429.             stream->outputBufferSize*sizeof(short)*stream->numChannels);  
  430.         if(stream->outputBuffer == NULL) {  
  431.             return 0;  
  432.         }  
  433.     }  
  434.     return 1;  
  435. }  
  436.   
  437. /* Enlarge the input buffer if needed. */  
  438. // 如果需要的话增大输入缓冲区  
  439. static int enlargeInputBufferIfNeeded(  
  440.     sonicStream stream,  
  441.     int numSamples)  
  442. {  
  443.     // 流中已经有的采样数据的大小 + 新的采样点个数  
  444.     if(stream->numInputSamples + numSamples > stream->inputBufferSize) {  
  445.         stream->inputBufferSize += (stream->inputBufferSize >> 1) + numSamples;  
  446.         // 重新设置内存空间的大小  
  447.         stream->inputBuffer = (short *)realloc(stream->inputBuffer,  
  448.             stream->inputBufferSize*sizeof(short)*stream->numChannels);  
  449.         if(stream->inputBuffer == NULL) {  
  450.             return 0;  
  451.         }  
  452.     }  
  453.     return 1;  
  454. }  
  455.   
  456. /* Add the input samples to the input buffer. */  
  457. // 向流的输入缓冲区中写入float格式的采样数据  
  458. static int addFloatSamplesToInputBuffer(  
  459.     sonicStream stream,  
  460.     float *samples,  
  461.     int numSamples)  
  462. {  
  463.     short *buffer;  
  464.     int count = numSamples*stream->numChannels;  
  465.   
  466.     if(numSamples == 0) {  
  467.         return 1;  
  468.     }  
  469.     if(!enlargeInputBufferIfNeeded(stream, numSamples)) {  
  470.         return 0;  
  471.     }  
  472.     buffer = stream->inputBuffer + stream->numInputSamples*stream->numChannels;  
  473.     while(count--) {  
  474.         *buffer++ = (*samples++)*32767.0f;  
  475.     }  
  476.     stream->numInputSamples += numSamples;  
  477.     return 1;  
  478. }  
  479.   
  480. /* Add the input samples to the input buffer. */  
  481. // 向流的输入缓冲区中写入short类型的数据  
  482. static int addShortSamplesToInputBuffer(  
  483.     sonicStream stream,  
  484.     short *samples,  
  485.     int numSamples)  
  486. {  
  487.     if(numSamples == 0) {  
  488.         return 1;  
  489.     }  
  490.     if(!enlargeInputBufferIfNeeded(stream, numSamples)) {  
  491.         return 0;  
  492.     }  
  493.     // 向输入缓冲区拷贝数据,重设numInputSamples大小  
  494.     memcpy(stream->inputBuffer + stream->numInputSamples*stream->numChannels, samples,  
  495.         numSamples*sizeof(short)*stream->numChannels);  
  496.     stream->numInputSamples += numSamples;  
  497.     return 1;  
  498. }  
  499.   
  500. /* Add the input samples to the input buffer. */  
  501. // 向流的输如缓冲区中写入unsigned格式的采样数据  
  502. static int addUnsignedCharSamplesToInputBuffer(  
  503.     sonicStream stream,  
  504.     unsigned char *samples,  
  505.     int numSamples)  
  506. {  
  507.     short *buffer;  
  508.     int count = numSamples*stream->numChannels;  
  509.   
  510.     if(numSamples == 0) {  
  511.         return 1;  
  512.     }  
  513.     if(!enlargeInputBufferIfNeeded(stream, numSamples)) {  
  514.         return 0;  
  515.     }  
  516.     buffer = stream->inputBuffer + stream->numInputSamples*stream->numChannels;  
  517.     while(count--) {  
  518.         *buffer++ = (*samples++ - 128) << 8;  
  519.     }  
  520.     stream->numInputSamples += numSamples;  
  521.     return 1;  
  522. }  
  523.   
  524. /* Remove input samples that we have already processed. */  
  525. // 移除已经处理过的输入缓冲区中的数据  
  526. static void removeInputSamples(  
  527.     sonicStream stream,  
  528.     int position)  
  529. {  
  530.     int remainingSamples = stream->numInputSamples - position;  
  531.   
  532.     if(remainingSamples > 0) {  
  533.         memmove(stream->inputBuffer, stream->inputBuffer + position*stream->numChannels,  
  534.             remainingSamples*sizeof(short)*stream->numChannels);  
  535.     }  
  536.     stream->numInputSamples = remainingSamples;  
  537. }  
  538.   
  539. /* Just copy from the array to the output buffer */  
  540. // 拷贝数组到输出缓冲区  
  541. static int copyToOutput(  
  542.     sonicStream stream,  
  543.     short *samples,  
  544.     int numSamples)  
  545. {  
  546.     if(!enlargeOutputBufferIfNeeded(stream, numSamples)) {  
  547.         return 0;  
  548.     }  
  549.     memcpy(stream->outputBuffer + stream->numOutputSamples*stream->numChannels,  
  550.         samples, numSamples*sizeof(short)*stream->numChannels);  
  551.     stream->numOutputSamples += numSamples;  
  552.     return 1;  
  553. }  
  554.   
  555. /* Just copy from the input buffer to the output buffer.  Return 0 if we fail to 
  556.    resize the output buffer.  Otherwise, return numSamples */  
  557. // 仅仅把输入缓冲区中的数据拷贝到输出缓冲区中,返回转移了的采样点的个数  
  558. // position表示偏移量  
  559. static int copyInputToOutput(  
  560.     sonicStream stream,  
  561.     int position)  
  562. {  
  563.     int numSamples = stream->remainingInputToCopy;  
  564.     //  
  565.     if(numSamples > stream->maxRequired) {  
  566.         numSamples = stream->maxRequired;  
  567.     }  
  568.     if(!copyToOutput(stream, stream->inputBuffer + position*stream->numChannels,  
  569.             numSamples)) {  
  570.         return 0;  
  571.     }  
  572.     // 剩余需要拷贝的输入缓冲区的采样点数  
  573.     stream->remainingInputToCopy -= numSamples;  
  574.     return numSamples;  
  575. }  
  576.   
  577. /* Read data out of the stream.  Sometimes no data will be available, and zero 
  578.    is returned, which is not an error condition. */  
  579. int sonicReadFloatFromStream(  
  580.     sonicStream stream,  
  581.     float *samples,  
  582.     int maxSamples)  
  583. {  
  584.     int numSamples = stream->numOutputSamples;  
  585.     int remainingSamples = 0;  
  586.     short *buffer;  
  587.     int count;  
  588.   
  589.     if(numSamples == 0) {  
  590.         return 0;  
  591.     }  
  592.     if(numSamples > maxSamples) {  
  593.         remainingSamples = numSamples - maxSamples;  
  594.         numSamples = maxSamples;  
  595.     }  
  596.     buffer = stream->outputBuffer;  
  597.     count = numSamples*stream->numChannels;  
  598.     while(count--) {  
  599.         *samples++ = (*buffer++)/32767.0f;  
  600.     }  
  601.     if(remainingSamples > 0) {  
  602.         memmove(stream->outputBuffer, stream->outputBuffer + numSamples*stream->numChannels,  
  603.             remainingSamples*sizeof(short)*stream->numChannels);  
  604.     }  
  605.     stream->numOutputSamples = remainingSamples;  
  606.     return numSamples;  
  607. }  
  608.   
  609. /* Read short data out of the stream.  Sometimes no data will be available, and zero 
  610.    is returned, which is not an error condition. */  
  611. // 从流中读取short类型的数据,如果没有数据返回0  
  612. int sonicReadShortFromStream(  
  613.     sonicStream stream,  
  614.     short *samples,  
  615.     int maxSamples)  
  616. {  
  617.     int numSamples = stream->numOutputSamples;  
  618.     int remainingSamples = 0;  
  619.   
  620.     if(numSamples == 0) {  
  621.         return 0;  
  622.     }  
  623.     if(numSamples > maxSamples) {  
  624.         remainingSamples = numSamples - maxSamples;  
  625.         numSamples = maxSamples;  
  626.     }  
  627.     memcpy(samples, stream->outputBuffer, numSamples*sizeof(short)*stream->numChannels);  
  628.     if(remainingSamples > 0) {  
  629.         memmove(stream->outputBuffer, stream->outputBuffer + numSamples*stream->numChannels,  
  630.             remainingSamples*sizeof(short)*stream->numChannels);  
  631.     }  
  632.     stream->numOutputSamples = remainingSamples;  
  633.     return numSamples;  
  634. }  
  635.   
  636. /* Read unsigned char data out of the stream.  Sometimes no data will be available, and zero 
  637.    is returned, which is not an error condition. */  
  638. int sonicReadUnsignedCharFromStream(  
  639.     sonicStream stream,  
  640.     unsigned char *samples,  
  641.     int maxSamples)  
  642. {  
  643.     int numSamples = stream->numOutputSamples;  
  644.     int remainingSamples = 0;  
  645.     short *buffer;  
  646.     int count;  
  647.   
  648.     if(numSamples == 0) {  
  649.         return 0;  
  650.     }  
  651.     if(numSamples > maxSamples) {  
  652.         remainingSamples = numSamples - maxSamples;  
  653.         numSamples = maxSamples;  
  654.     }  
  655.     buffer = stream->outputBuffer;  
  656.     count = numSamples*stream->numChannels;  
  657.     while(count--) {  
  658.         *samples++ = (char)((*buffer++) >> 8) + 128;  
  659.     }  
  660.     if(remainingSamples > 0) {  
  661.         memmove(stream->outputBuffer, stream->outputBuffer + numSamples*stream->numChannels,  
  662.             remainingSamples*sizeof(short)*stream->numChannels);  
  663.     }  
  664.     stream->numOutputSamples = remainingSamples;  
  665.     return numSamples;  
  666. }  
  667.   
  668. /* Force the sonic stream to generate output using whatever data it currently 
  669.    has.  No extra delay will be added to the output, but flushing in the middle of 
  670.    words could introduce distortion. */  
  671. int sonicFlushStream(  
  672.     sonicStream stream)  
  673. {  
  674.     int maxRequired = stream->maxRequired;  
  675.     int remainingSamples = stream->numInputSamples;  
  676.     float speed = stream->speed/stream->pitch;  
  677.     float rate = stream->rate*stream->pitch;  
  678.     int expectedOutputSamples = stream->numOutputSamples +  
  679.         (int)((remainingSamples/speed + stream->numPitchSamples)/rate + 0.5f);  
  680.   
  681.     /* Add enough silence to flush both input and pitch buffers. */  
  682.     if(!enlargeInputBufferIfNeeded(stream, remainingSamples + 2*maxRequired)) {  
  683.         return 0;  
  684.     }  
  685.     memset(stream->inputBuffer + remainingSamples*stream->numChannels, 0,  
  686.         2*maxRequired*sizeof(short)*stream->numChannels);  
  687.     stream->numInputSamples += 2*maxRequired;  
  688.     if(!sonicWriteShortToStream(stream, NULL, 0)) {  
  689.         return 0;  
  690.     }  
  691.     /* Throw away any extra samples we generated due to the silence we added */  
  692.     if(stream->numOutputSamples > expectedOutputSamples) {  
  693.         stream->numOutputSamples = expectedOutputSamples;  
  694.     }  
  695.     /* Empty input and pitch buffers */  
  696.     stream->numInputSamples = 0;  
  697.     stream->remainingInputToCopy = 0;  
  698.     stream->numPitchSamples = 0;  
  699.     return 1;  
  700. }  
  701.   
  702. /* Return the number of samples in the output buffer */  
  703. int sonicSamplesAvailable(  
  704.    sonicStream stream)  
  705. {  
  706.     return stream->numOutputSamples;  
  707. }  
  708.   
  709. /* If skip is greater than one, average skip samples together and write them to 
  710.    the down-sample buffer.  If numChannels is greater than one, mix the channels 
  711.    together as we down sample. */  
  712. static void downSampleInput(  
  713.     sonicStream stream,  
  714.     short *samples,  
  715.     int skip)  
  716. {  
  717.     int numSamples = stream->maxRequired/skip;  
  718.     int samplesPerValue = stream->numChannels*skip;  
  719.     int i, j;  
  720.     int value;  
  721.     short *downSamples = stream->downSampleBuffer;  
  722.   
  723.     for(i = 0; i < numSamples; i++) {  
  724.         value = 0;  
  725.         for(j = 0; j < samplesPerValue; j++) {  
  726.             value += *samples++;  
  727.         }  
  728.         value /= samplesPerValue;  
  729.         *downSamples++ = value;  
  730.     }  
  731. }  
  732.   
  733. /* Find the best frequency match in the range, and given a sample skip multiple. 
  734.    For now, just find the pitch of the first channel. */  
  735. static int findPitchPeriodInRange(  
  736.     short *samples,  
  737.     int minPeriod,  
  738.     int maxPeriod,  
  739.     int *retMinDiff,  
  740.     int *retMaxDiff)  
  741. {  
  742.     int period, bestPeriod = 0, worstPeriod = 255;  
  743.     short *s, *p, sVal, pVal;  
  744.     unsigned long diff, minDiff = 1, maxDiff = 0;  
  745.     int i;  
  746.   
  747.     for(period = minPeriod; period <= maxPeriod; period++) {  
  748.         diff = 0;  
  749.         s = samples;  
  750.         p = samples + period;  
  751.         for(i = 0; i < period; i++) {  
  752.             sVal = *s++;  
  753.             pVal = *p++;  
  754.             diff += sVal >= pVal? (unsigned short)(sVal - pVal) :  
  755.                 (unsigned short)(pVal - sVal);  
  756.         }  
  757.         /* Note that the highest number of samples we add into diff will be less 
  758.            than 256, since we skip samples.  Thus, diff is a 24 bit number, and 
  759.            we can safely multiply by numSamples without overflow */  
  760.         /* if (bestPeriod == 0 || (bestPeriod*3/2 > period && diff*bestPeriod < minDiff*period) || 
  761.                 diff*bestPeriod < (minDiff >> 1)*period) {*/  
  762.         if (bestPeriod == 0 || diff*bestPeriod < minDiff*period) {  
  763.             minDiff = diff;  
  764.             bestPeriod = period;  
  765.         }  
  766.         if(diff*worstPeriod > maxDiff*period) {  
  767.             maxDiff = diff;  
  768.             worstPeriod = period;  
  769.         }  
  770.     }  
  771.     *retMinDiff = minDiff/bestPeriod;  
  772.     *retMaxDiff = maxDiff/worstPeriod;  
  773.     return bestPeriod;  
  774. }  
  775.   
  776. /* At abrupt ends of voiced words, we can have pitch periods that are better 
  777.    approximated by the previous pitch period estimate.  Try to detect this case. */  
  778. static int prevPeriodBetter(  
  779.     sonicStream stream,  
  780.     int period,  
  781.     int minDiff,  
  782.     int maxDiff,  
  783.     int preferNewPeriod)  
  784. {  
  785.     if(minDiff == 0 || stream->prevPeriod == 0) {  
  786.         return 0;  
  787.     }  
  788.     if(preferNewPeriod) {  
  789.         if(maxDiff > minDiff*3) {  
  790.             /* Got a reasonable match this period */  
  791.             return 0;  
  792.         }  
  793.         if(minDiff*2 <= stream->prevMinDiff*3) {  
  794.             /* Mismatch is not that much greater this period */  
  795.             return 0;  
  796.         }  
  797.     } else {  
  798.         if(minDiff <= stream->prevMinDiff) {  
  799.             return 0;  
  800.         }  
  801.     }  
  802.     return 1;  
  803. }  
  804.   
  805. /* Find the pitch period.  This is a critical step, and we may have to try 
  806.    multiple ways to get a good answer.  This version uses Average Magnitude 
  807.    Difference Function (AMDF).  To improve speed, we down sample by an integer 
  808.    factor get in the 11KHz range, and then do it again with a narrower 
  809.    frequency range without down sampling */  
  810. static int findPitchPeriod(  
  811.     sonicStream stream,  
  812.     short *samples,  
  813.     int preferNewPeriod)  
  814. {  
  815.     int minPeriod = stream->minPeriod;  
  816.     int maxPeriod = stream->maxPeriod;  
  817.     int sampleRate = stream->sampleRate;  
  818.     int minDiff, maxDiff, retPeriod;  
  819.     int skip = 1;  
  820.     int period;  
  821.   
  822.     if(sampleRate > SONIC_AMDF_FREQ && stream->quality == 0) {  
  823.         skip = sampleRate/SONIC_AMDF_FREQ;  
  824.     }  
  825.     if(stream->numChannels == 1 && skip == 1) {  
  826.         period = findPitchPeriodInRange(samples, minPeriod, maxPeriod, &minDiff, &maxDiff);  
  827.     } else {  
  828.         downSampleInput(stream, samples, skip);  
  829.         period = findPitchPeriodInRange(stream->downSampleBuffer, minPeriod/skip,  
  830.             maxPeriod/skip, &minDiff, &maxDiff);  
  831.         if(skip != 1) {  
  832.             period *= skip;  
  833.             minPeriod = period - (skip << 2);  
  834.             maxPeriod = period + (skip << 2);  
  835.             if(minPeriod < stream->minPeriod) {  
  836.                 minPeriod = stream->minPeriod;  
  837.             }  
  838.             if(maxPeriod > stream->maxPeriod) {  
  839.                 maxPeriod = stream->maxPeriod;  
  840.             }  
  841.             if(stream->numChannels == 1) {  
  842.                 period = findPitchPeriodInRange(samples, minPeriod, maxPeriod,  
  843.                     &minDiff, &maxDiff);  
  844.             } else {  
  845.                 downSampleInput(stream, samples, 1);  
  846.                 period = findPitchPeriodInRange(stream->downSampleBuffer, minPeriod,  
  847.                     maxPeriod, &minDiff, &maxDiff);  
  848.             }  
  849.         }  
  850.     }  
  851.     if(prevPeriodBetter(stream, period, minDiff, maxDiff, preferNewPeriod)) {  
  852.         retPeriod = stream->prevPeriod;  
  853.     } else {  
  854.         retPeriod = period;  
  855.     }  
  856.     stream->prevMinDiff = minDiff;  
  857.     stream->prevPeriod = period;  
  858.     return retPeriod;  
  859. }  
  860.   
  861. /* Overlap two sound segments, ramp the volume of one down, while ramping the 
  862.    other one from zero up, and add them, storing the result at the output. */  
  863. static void overlapAdd(  
  864.     int numSamples,  
  865.     int numChannels,  
  866.     short *out,  
  867.     short *rampDown,  
  868.     short *rampUp)  
  869. {  
  870.     short *o, *u, *d;  
  871.     int i, t;  
  872.   
  873.     for(i = 0; i < numChannels; i++) {  
  874.         o = out + i;  
  875.         u = rampUp + i;  
  876.         d = rampDown + i;  
  877.         for(t = 0; t < numSamples; t++) {  
  878. #ifdef SONIC_USE_SIN  
  879.             float ratio = sin(t*M_PI/(2*numSamples));  
  880.             *o = *d*(1.0f - ratio) + *u*ratio;  
  881. #else  
  882.             *o = (*d*(numSamples - t) + *u*t)/numSamples;  
  883. #endif  
  884.             o += numChannels;  
  885.             d += numChannels;  
  886.             u += numChannels;  
  887.         }  
  888.     }  
  889. }  
  890.   
  891. /* Overlap two sound segments, ramp the volume of one down, while ramping the 
  892.    other one from zero up, and add them, storing the result at the output. */  
  893. static void overlapAddWithSeparation(  
  894.     int numSamples,  
  895.     int numChannels,  
  896.     int separation,  
  897.     short *out,  
  898.     short *rampDown,  
  899.     short *rampUp)  
  900. {  
  901.     short *o, *u, *d;  
  902.     int i, t;  
  903.   
  904.     for(i = 0; i < numChannels; i++) {  
  905.         o = out + i;  
  906.         u = rampUp + i;  
  907.         d = rampDown + i;  
  908.         for(t = 0; t < numSamples + separation; t++) {  
  909.             if(t < separation) {  
  910.                 *o = *d*(numSamples - t)/numSamples;  
  911.                 d += numChannels;  
  912.             } else if(t < numSamples) {  
  913.                 *o = (*d*(numSamples - t) + *u*(t - separation))/numSamples;  
  914.                 d += numChannels;  
  915.                 u += numChannels;  
  916.             } else {  
  917.                 *o = *u*(t - separation)/numSamples;  
  918.                 u += numChannels;  
  919.             }  
  920.             o += numChannels;  
  921.         }  
  922.     }  
  923. }  
  924.   
  925. /* Just move the new samples in the output buffer to the pitch buffer */  
  926. static int moveNewSamplesToPitchBuffer(  
  927.     sonicStream stream,  
  928.     int originalNumOutputSamples)  
  929. {  
  930.     int numSamples = stream->numOutputSamples - originalNumOutputSamples;  
  931.     int numChannels = stream->numChannels;  
  932.   
  933.     if(stream->numPitchSamples + numSamples > stream->pitchBufferSize) {  
  934.         stream->pitchBufferSize += (stream->pitchBufferSize >> 1) + numSamples;  
  935.         stream->pitchBuffer = (short *)realloc(stream->pitchBuffer,  
  936.             stream->pitchBufferSize*sizeof(short)*numChannels);  
  937.         if(stream->pitchBuffer == NULL) {  
  938.             return 0;  
  939.         }  
  940.     }  
  941.     memcpy(stream->pitchBuffer + stream->numPitchSamples*numChannels,  
  942.         stream->outputBuffer + originalNumOutputSamples*numChannels,  
  943.         numSamples*sizeof(short)*numChannels);  
  944.     stream->numOutputSamples = originalNumOutputSamples;  
  945.     stream->numPitchSamples += numSamples;  
  946.     return 1;  
  947. }  
  948.   
  949. /* Remove processed samples from the pitch buffer. */  
  950. static void removePitchSamples(  
  951.     sonicStream stream,  
  952.     int numSamples)  
  953. {  
  954.     int numChannels = stream->numChannels;  
  955.     short *source = stream->pitchBuffer + numSamples*numChannels;  
  956.   
  957.     if(numSamples == 0) {  
  958.         return;  
  959.     }  
  960.     if(numSamples != stream->numPitchSamples) {  
  961.         memmove(stream->pitchBuffer, source, (stream->numPitchSamples -  
  962.             numSamples)*sizeof(short)*numChannels);  
  963.     }  
  964.     stream->numPitchSamples -= numSamples;  
  965. }  
  966.   
  967. /* Change the pitch.  The latency this introduces could be reduced by looking at 
  968.    past samples to determine pitch, rather than future. */  
  969. static int adjustPitch(  
  970.     sonicStream stream,  
  971.     int originalNumOutputSamples)  
  972. {  
  973.     float pitch = stream->pitch;  
  974.     int numChannels = stream->numChannels;  
  975.     int period, newPeriod, separation;  
  976.     int position = 0;  
  977.     short *out, *rampDown, *rampUp;  
  978.   
  979.     if(stream->numOutputSamples == originalNumOutputSamples) {  
  980.         return 1;  
  981.     }  
  982.     if(!moveNewSamplesToPitchBuffer(stream, originalNumOutputSamples)) {  
  983.         return 0;  
  984.     }  
  985.     while(stream->numPitchSamples - position >= stream->maxRequired) {  
  986.         period = findPitchPeriod(stream, stream->pitchBuffer + position*numChannels, 0);  
  987.         newPeriod = period/pitch;  
  988.         if(!enlargeOutputBufferIfNeeded(stream, newPeriod)) {  
  989.             return 0;  
  990.         }  
  991.         out = stream->outputBuffer + stream->numOutputSamples*numChannels;  
  992.         if(pitch >= 1.0f) {  
  993.             rampDown = stream->pitchBuffer + position*numChannels;  
  994.             rampUp = stream->pitchBuffer + (position + period - newPeriod)*numChannels;  
  995.             overlapAdd(newPeriod, numChannels, out, rampDown, rampUp);  
  996.         } else {  
  997.             rampDown = stream->pitchBuffer + position*numChannels;  
  998.             rampUp = stream->pitchBuffer + position*numChannels;  
  999.             separation = newPeriod - period;  
  1000.             overlapAddWithSeparation(period, numChannels, separation, out, rampDown, rampUp);  
  1001.         }  
  1002.         stream->numOutputSamples += newPeriod;  
  1003.         position += period;  
  1004.     }  
  1005.     removePitchSamples(stream, position);  
  1006.     return 1;  
  1007. }  
  1008.   
  1009. /* Aproximate the sinc function times a Hann window from the sinc table. */  
  1010. static int findSincCoefficient(int i, int ratio, int width) {  
  1011.     int lobePoints = (SINC_TABLE_SIZE-1)/SINC_FILTER_POINTS;  
  1012.     int left = i*lobePoints + (ratio*lobePoints)/width;  
  1013.     int right = left + 1;  
  1014.     int position = i*lobePoints*width + ratio*lobePoints - left*width;  
  1015.     int leftVal = sincTable[left];  
  1016.     int rightVal = sincTable[right];  
  1017.   
  1018.     return ((leftVal*(width - position) + rightVal*position) << 1)/width;  
  1019. }  
  1020.   
  1021. /* Return 1 if value >= 0, else -1.  This represents the sign of value. */  
  1022. static int getSign(int value) {  
  1023.     return value >= 0? 1 : 0;  
  1024. }  
  1025.   
  1026. /* Interpolate the new output sample. */  
  1027. static short interpolate(  
  1028.     sonicStream stream,  
  1029.     short *in,  
  1030.     int oldSampleRate,  
  1031.     int newSampleRate)  
  1032. {  
  1033.     /* Compute N-point sinc FIR-filter here.  Clip rather than overflow. */  
  1034.     int i;  
  1035.     int total = 0;  
  1036.     int position = stream->newRatePosition*oldSampleRate;  
  1037.     int leftPosition = stream->oldRatePosition*newSampleRate;  
  1038.     int rightPosition = (stream->oldRatePosition + 1)*newSampleRate;  
  1039.     int ratio = rightPosition - position - 1;  
  1040.     int width = rightPosition - leftPosition;  
  1041.     int weight, value;  
  1042.     int oldSign;  
  1043.     int overflowCount = 0;  
  1044.   
  1045.     for (i = 0; i < SINC_FILTER_POINTS; i++) {  
  1046.         weight = findSincCoefficient(i, ratio, width);  
  1047.         /* printf("%u %f\n", i, weight); */  
  1048.         value = in[i*stream->numChannels]*weight;  
  1049.         oldSign = getSign(total);  
  1050.         total += value;  
  1051.         if (oldSign != getSign(total) && getSign(value) == oldSign) {  
  1052.             /* We must have overflowed.  This can happen with a sinc filter. */  
  1053.             overflowCount += oldSign;  
  1054.         }  
  1055.     }  
  1056.     /* It is better to clip than to wrap if there was a overflow. */  
  1057.     if (overflowCount > 0) {  
  1058.         return SHRT_MAX;  
  1059.     } else if (overflowCount < 0) {  
  1060.         return SHRT_MIN;  
  1061.     }  
  1062.     return total >> 16;  
  1063. }  
  1064.   
  1065. /* Change the rate.  Interpolate with a sinc FIR filter using a Hann window. */  
  1066. static int adjustRate(  
  1067.     sonicStream stream,  
  1068.     float rate,  
  1069.     int originalNumOutputSamples)  
  1070. {  
  1071.     int newSampleRate = stream->sampleRate/rate;  
  1072.     int oldSampleRate = stream->sampleRate;  
  1073.     int numChannels = stream->numChannels;  
  1074.     int position = 0;  
  1075.     short *in, *out;  
  1076.     int i;  
  1077.     int N = SINC_FILTER_POINTS;  
  1078.   
  1079.     /* Set these values to help with the integer math */  
  1080.     while(newSampleRate > (1 << 14) || oldSampleRate > (1 << 14)) {  
  1081.         newSampleRate >>= 1;  
  1082.         oldSampleRate >>= 1;  
  1083.     }  
  1084.     if(stream->numOutputSamples == originalNumOutputSamples) {  
  1085.         return 1;  
  1086.     }  
  1087.     if(!moveNewSamplesToPitchBuffer(stream, originalNumOutputSamples)) {  
  1088.         return 0;  
  1089.     }  
  1090.     /* Leave at least N pitch sample in the buffer */  
  1091.     for(position = 0; position < stream->numPitchSamples - N; position++) {  
  1092.         while((stream->oldRatePosition + 1)*newSampleRate >  
  1093.                 stream->newRatePosition*oldSampleRate) {  
  1094.             if(!enlargeOutputBufferIfNeeded(stream, 1)) {  
  1095.                 return 0;  
  1096.             }  
  1097.             out = stream->outputBuffer + stream->numOutputSamples*numChannels;  
  1098.             in = stream->pitchBuffer + position*numChannels;  
  1099.             for(i = 0; i < numChannels; i++) {  
  1100.                 *out++ = interpolate(stream, in, oldSampleRate, newSampleRate);  
  1101.                 in++;  
  1102.             }  
  1103.             stream->newRatePosition++;  
  1104.             stream->numOutputSamples++;  
  1105.         }  
  1106.         stream->oldRatePosition++;  
  1107.         if(stream->oldRatePosition == oldSampleRate) {  
  1108.             stream->oldRatePosition = 0;  
  1109.             if(stream->newRatePosition != newSampleRate) {  
  1110.                 fprintf(stderr,  
  1111.                     "Assertion failed: stream->newRatePosition != newSampleRate\n");  
  1112.                 exit(1);  
  1113.             }  
  1114.             stream->newRatePosition = 0;  
  1115.         }  
  1116.     }  
  1117.     removePitchSamples(stream, position);  
  1118.     return 1;  
  1119. }  
  1120.   
  1121. /* Skip over a pitch period, and copy period/speed samples to the output */  
  1122. static int skipPitchPeriod(  
  1123.     sonicStream stream,  
  1124.     short *samples,  
  1125.     float speed,  
  1126.     int period)  
  1127. {  
  1128.     long newSamples;  
  1129.     int numChannels = stream->numChannels;  
  1130.   
  1131.     if(speed >= 2.0f) {  
  1132.         newSamples = period/(speed - 1.0f);  
  1133.     } else {  
  1134.         newSamples = period;  
  1135.         stream->remainingInputToCopy = period*(2.0f - speed)/(speed - 1.0f);  
  1136.     }  
  1137.     if(!enlargeOutputBufferIfNeeded(stream, newSamples)) {  
  1138.         return 0;  
  1139.     }  
  1140.     overlapAdd(newSamples, numChannels, stream->outputBuffer +  
  1141.         stream->numOutputSamples*numChannels, samples, samples + period*numChannels);  
  1142.     stream->numOutputSamples += newSamples;  
  1143.     return newSamples;  
  1144. }  
  1145.   
  1146. /* Insert a pitch period, and determine how much input to copy directly. */  
  1147. static int insertPitchPeriod(  
  1148.     sonicStream stream,  
  1149.     short *samples,  
  1150.     float speed,  
  1151.     int period)  
  1152. {  
  1153.     long newSamples;  
  1154.     short *out;  
  1155.     int numChannels = stream->numChannels;  
  1156.   
  1157.     if(speed < 0.5f) {  
  1158.         newSamples = period*speed/(1.0f - speed);  
  1159.     } else {  
  1160.         newSamples = period;  
  1161.         stream->remainingInputToCopy = period*(2.0f*speed - 1.0f)/(1.0f - speed);  
  1162.     }  
  1163.     if(!enlargeOutputBufferIfNeeded(stream, period + newSamples)) {  
  1164.         return 0;  
  1165.     }  
  1166.     out = stream->outputBuffer + stream->numOutputSamples*numChannels;  
  1167.     memcpy(out, samples, period*sizeof(short)*numChannels);  
  1168.     out = stream->outputBuffer + (stream->numOutputSamples + period)*numChannels;  
  1169.     overlapAdd(newSamples, numChannels, out, samples + period*numChannels, samples);  
  1170.     stream->numOutputSamples += period + newSamples;  
  1171.     return newSamples;  
  1172. }  
  1173.   
  1174. /* Resample as many pitch periods as we have buffered on the input.  Return 0 if 
  1175.    we fail to resize an input or output buffer. */  
  1176. // 尽可能多的重采样输入缓冲区中的基音周期,如果成功返回非0  
  1177. static int changeSpeed(  
  1178.     sonicStream stream,  
  1179.     float speed)  
  1180. {  
  1181.     short *samples;  
  1182.     int numSamples = stream->numInputSamples;  
  1183.     int position = 0, period, newSamples;  
  1184.     int maxRequired = stream->maxRequired;  
  1185.   
  1186.     /* printf("Changing speed to %f\n", speed); */  
  1187.     if(stream->numInputSamples < maxRequired) {  
  1188.         return 1;  
  1189.     }  
  1190.     do {  
  1191.         // 流中剩余的采样点的个数  
  1192.         if(stream->remainingInputToCopy > 0) {  
  1193.             //  
  1194.             newSamples = copyInputToOutput(stream, position);  
  1195.             position += newSamples;  
  1196.         } else {  
  1197.             samples = stream->inputBuffer + position*stream->numChannels;  
  1198.             period = findPitchPeriod(stream, samples, 1);  
  1199.             if(speed > 1.0) {  
  1200.                 newSamples = skipPitchPeriod(stream, samples, speed, period);  
  1201.                 position += period + newSamples;  
  1202.             } else {  
  1203.                 newSamples = insertPitchPeriod(stream, samples, speed, period);  
  1204.                 position += newSamples;  
  1205.             }  
  1206.         }  
  1207.         if(newSamples == 0) {  
  1208.             return 0; /* Failed to resize output buffer */  
  1209.         }  
  1210.     } while(position + maxRequired <= numSamples);  
  1211.     removeInputSamples(stream, position);  
  1212.     return 1;  
  1213. }  
  1214.   
  1215. /* Resample as many pitch periods as we have buffered on the input.  Return 0 if 
  1216.    we fail to resize an input or output buffer.  Also scale the output by the volume. */  
  1217. // 尽可能多的将输入缓冲区中的基音周期进行重采样,如果失败返回0,如果成功返回1。同时也scale了音量  
  1218. static int processStreamInput(  
  1219.     sonicStream stream)  
  1220. {  
  1221.     // 流中输出缓冲区中原有的采样点的数量  
  1222.     int originalNumOutputSamples = stream->numOutputSamples;  
  1223.     // 速度  
  1224.     float speed = stream->speed/stream->pitch;  
  1225.     float rate = stream->rate;  
  1226.     // 如果不用chordPitch  
  1227.     if(!stream->useChordPitch) {  
  1228.         rate *= stream->pitch;  
  1229.     }  
  1230.     // 改变速度  
  1231.     if(speed > 1.00001 || speed < 0.99999) {  
  1232.         changeSpeed(stream, speed);  
  1233.     } else {  
  1234.         if(!copyToOutput(stream, stream->inputBuffer, stream->numInputSamples)) {  
  1235.             return 0;  
  1236.         }  
  1237.         stream->numInputSamples = 0;  
  1238.     }  
  1239.     if(stream->useChordPitch) {  
  1240.         if(stream->pitch != 1.0f) {  
  1241.             if(!adjustPitch(stream, originalNumOutputSamples)) {  
  1242.                 return 0;  
  1243.             }  
  1244.         }  
  1245.     } else if(rate != 1.0f) {  
  1246.         if(!adjustRate(stream, rate, originalNumOutputSamples)) {  
  1247.             return 0;  
  1248.         }  
  1249.     }  
  1250.     if(stream->volume != 1.0f) {  
  1251.         /* Adjust output volume. */  
  1252.         scaleSamples(stream->outputBuffer + originalNumOutputSamples*stream->numChannels,  
  1253.             (stream->numOutputSamples - originalNumOutputSamples)*stream->numChannels,  
  1254.             stream->volume);  
  1255.     }  
  1256.     return 1;  
  1257. }  
  1258.   
  1259. /* Write floating point data to the input buffer and process it. */  
  1260. int sonicWriteFloatToStream(  
  1261.     sonicStream stream,  
  1262.     float *samples,  
  1263.     int numSamples)  
  1264. {  
  1265.     if(!addFloatSamplesToInputBuffer(stream, samples, numSamples)) {  
  1266.         return 0;  
  1267.     }  
  1268.     return processStreamInput(stream);  
  1269. }  
  1270.   
  1271. /* Simple wrapper around sonicWriteFloatToStream that does the short to float 
  1272.    conversion for you. */  
  1273.    // 向流中写入short类型的数据并进行处理  
  1274. int sonicWriteShortToStream(  
  1275.     sonicStream stream,  
  1276.     short *samples,  
  1277.     int numSamples)  
  1278. {  
  1279.     if(!addShortSamplesToInputBuffer(stream, samples, numSamples)) {  
  1280.         return 0;  
  1281.     }  
  1282.     // 处理输入流的数据  
  1283.     return processStreamInput(stream);  
  1284. }  
  1285.   
  1286. /* Simple wrapper around sonicWriteFloatToStream that does the unsigned char to float 
  1287.    conversion for you. */  
  1288. int sonicWriteUnsignedCharToStream(  
  1289.     sonicStream stream,  
  1290.     unsigned char *samples,  
  1291.     int numSamples)  
  1292. {  
  1293.     if(!addUnsignedCharSamplesToInputBuffer(stream, samples, numSamples)) {  
  1294.         return 0;  
  1295.     }  
  1296.     return processStreamInput(stream);  
  1297. }  
  1298.   
  1299. /* This is a non-stream oriented interface to just change the speed of a sound sample */  
  1300. int sonicChangeFloatSpeed(  
  1301.     float *samples,  
  1302.     int numSamples,  
  1303.     float speed,  
  1304.     float pitch,  
  1305.     float rate,  
  1306.     float volume,  
  1307.     int useChordPitch,  
  1308.     int sampleRate,  
  1309.     int numChannels)  
  1310. {  
  1311.     sonicStream stream = sonicCreateStream(sampleRate, numChannels);  
  1312.   
  1313.     sonicSetSpeed(stream, speed);  
  1314.     sonicSetPitch(stream, pitch);  
  1315.     sonicSetRate(stream, rate);  
  1316.     sonicSetVolume(stream, volume);  
  1317.     sonicSetChordPitch(stream, useChordPitch);  
  1318.     sonicWriteFloatToStream(stream, samples, numSamples);  
  1319.     sonicFlushStream(stream);  
  1320.     numSamples = sonicSamplesAvailable(stream);  
  1321.     sonicReadFloatFromStream(stream, samples, numSamples);  
  1322.     sonicDestroyStream(stream);  
  1323.     return numSamples;  
  1324. }  
  1325.   
  1326. /* This is a non-stream oriented interface to just change the speed of a sound sample */  
  1327. int sonicChangeShortSpeed(  
  1328.     short *samples,  
  1329.     int numSamples,  
  1330.     float speed,  
  1331.     float pitch,  
  1332.     float rate,  
  1333.     float volume,  
  1334.     int useChordPitch,  
  1335.     int sampleRate,  
  1336.     int numChannels)  
  1337. {   // 创建并初始化流  
  1338.     sonicStream stream = sonicCreateStream(sampleRate, numChannels);  
  1339.     // 设置流的速度  
  1340.     sonicSetSpeed(stream, speed);  
  1341.     // 设置流的音调  
  1342.     sonicSetPitch(stream, pitch);  
  1343.     // 设置流的速率  
  1344.     sonicSetRate(stream, rate);  
  1345.     // 设置流的音量  
  1346.     sonicSetVolume(stream, volume);  
  1347.     // 设置  
  1348.     sonicSetChordPitch(stream, useChordPitch);  
  1349.     // 向流中写入short类型的数据  
  1350.     sonicWriteShortToStream(stream, samples, numSamples);  
  1351.     sonicFlushStream(stream);  
  1352.     numSamples = sonicSamplesAvailable(stream);  
  1353.     sonicReadShortFromStream(stream, samples, numSamples);  
  1354.     sonicDestroyStream(stream);  
  1355.     return numSamples;  
  1356. }  


采用的方法:

        方法分为基于流和不基于流(基于音频buffer数组)的两种,原始说明文件在这儿,我采用了基于流的方法,因为不基于流的方法由于解码一帧数据会flush掉数组中剩下的没有处理的数据并填充空数据,会产生刺啦刺啦的声音。


[cpp]  view plain  copy
  1. // 初始化部分:先创建一个流  
  2. sonicStream tempoStream_;  
  3. // 参数为采样率和声道数  
  4. tempoStream_ = sonicCreateStream(44100, 1);  
  5.   
  6. ………………  
  7.   
  8. // 数据处理部分:  
  9. // 首先要有一个音频数据 short* pcm_buffer,大小为 buffer_size  
  10. // 还要有需要转换的速率 float speed  
  11. // 设置流的速率  
  12. sonicSetSpeed(tempoStream_, speed);  
  13. // 向流中写入pcm_buffer  
  14. int ret = sonicWriteShortToStream(tempoStream_, pcm_buffer, buffer_size);  
  15. // 计算处理后的点数  
  16. int numSamples = buffer_size / speed;  
  17. if(ret) {  
  18. // 从流中读取处理好的数据  
  19.    int new_buffer_size = sonicReadShortFromStream(tempoStream_, pcm_buffer, numSamples);  
  20. }  

搞定,转换完速率的音频数据已经存在pcm_buffer里面了,拿着去玩儿吧
Logo

致力于链接即构和开发者,提供实时互动和元宇宙领域的前沿洞察、技术分享和丰富的开发者活动,共建实时互动世界。

更多推荐