近一段时间在图像算法以及音频算法之间来回游走。
经常有一些需求,需要将音频进行采样转码处理。
现有的知名开源库,诸如: webrtc , sox等,
代码阅读起来实在闹心。
而音频重采样其实也就是插值算法。
与图像方面的插值算法没有太大的区别。
基于双线性插值的思路。
博主简单实现一个简洁的重采样算法,
用在对采样音质要求不高的情况下,也是够用了。
编解码库采用dr_wav
https://github.com/mackron/dr_libs/blob/master/dr_wav.h
近期有点强迫症,纯c实现。
贴上完整代码:
#ifdef __cplusplus extern "C" { #endif #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <stdint.h> #define DR_WAV_IMPLEMENTATION #include "dr_wav.h" #define DR_MP3_IMPLEMENTATION #include "dr_mp3.h" #include "timing.h" void wavWrite_f32(char *filename, float *buffer, int sampleRate, uint32_t totalSampleCount, uint32_t channels) { drwav_data_format format; format.container = drwav_container_riff; format.format = DR_WAVE_FORMAT_IEEE_FLOAT; format.channels = channels; format.sampleRate = (drwav_uint32) sampleRate; format.bitsPerSample = 32; drwav *pWav = drwav_open_file_write(filename, &format); if (pWav) { drwav_uint64 samplesWritten = drwav_write(pWav, totalSampleCount, buffer); drwav_uninit(pWav); if (samplesWritten != totalSampleCount) { fprintf(stderr, "write file [%s] error. ", filename); exit(1); } } } float *wavRead_f32(const char *filename, uint32_t *sampleRate, uint64_t *sampleCount, uint32_t *channels) { drwav_uint64 totalSampleCount = 0; float *input = drwav_open_file_and_read_pcm_frames_f32(filename, channels, sampleRate, &totalSampleCount); if (input == NULL) { drmp3_config pConfig; input = drmp3_open_file_and_read_f32(filename, &pConfig, &totalSampleCount); if (input != NULL) { *channels = pConfig.outputChannels; *sampleRate = pConfig.outputSampleRate; } } if (input == NULL) { fprintf(stderr, "read file [%s] error. ", filename); exit(1); } *sampleCount = totalSampleCount * (*channels); return input; } void splitpath(const char *path, char *drv, char *dir, char *name, char *ext) { const char *end; const char *p; const char *s; if (path[0] && path[1] == ':') { if (drv) { *drv++ = *path++; *drv++ = *path++; *drv = '