写代码,让你的声音变得高亢
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了写代码,让你的声音变得高亢相关的知识,希望对你有一定的参考价值。
小白:我是标准的男中音,唱“李香兰”不输张学友,为什么我要变成女高音?
本文介绍,如何修改音频数据,控制音频的节奏、速率或音调。
大概的思路是这样的,先解码音频,得到pcm数据,再通过soundtouch来修改pcm数据,最后压缩为常见格式的音频。
对于音频编码格式之类的知识,可以参考之前同系列的文章。
先给出一个经过修改后的音频文件,可以听一下效果(如果这里可以上传并播放音频文件的话):
解码与编码部分,同样是FFmpeg的使用(之前多次介绍过了),得到pcm后再调用soundtouch。
演示demo的文件结构:
先上代码(change_pcm_pitch.cpp),之后再简单介绍soundtouch及它的调用:
extern "C" {
#include "ffmpeg/include/libavcodec/avcodec.h"
#include "ffmpeg/include/libavformat/avformat.h"
#include "ffmpeg/include/libswresample/swresample.h"
#include "ffmpeg/include/libavutil/samplefmt.h"
}
#include "SoundTouch.h"
using namespace soundtouch;
void change_pcm_pitch(const char* filepath) {
av_register_all();
av_log_set_level(AV_LOG_DEBUG);
AVFormatContext* formatContext = avformat_alloc_context();
AVCodecContext* codecContext = NULL;
int status = 0;
bool success = false;
int audioindex = -1;
status = avformat_open_input(&formatContext, filepath, NULL, NULL);
if (status == 0) {
status = avformat_find_stream_info(formatContext, NULL);
if (status >= 0) {
for (int i = 0; i < formatContext->nb_streams; i ++) {
if (formatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
audioindex = i;
break;
}
}
if (audioindex > -1) {
codecContext = formatContext->streams[audioindex]->codec;
AVCodec* codec = avcodec_find_decoder(codecContext->codec_id);
if (codec) {
status = avcodec_open2(codecContext, codec, NULL);
if (status == 0) {
success = true;
}
}
}
}
}
if (success) {
av_dump_format(formatContext, 0, filepath, false);
av_log(NULL, AV_LOG_DEBUG, "format and decoder sucessful, and now in decoding each frame\n");
printf("sample_rate=%d, channels=%d\n", codecContext->sample_rate, codecContext->channels);
SoundTouch* soundtouch = new SoundTouch();
printf("soundtouch version=%s\n", soundtouch->getVersionString());
soundtouch->setSampleRate(codecContext->sample_rate);
soundtouch->setChannels(codecContext->channels);
soundtouch->setTempo(0.5); // tempo,播放节奏,1.0为正常节奏,大于1.0加快,小于1.0变慢,pcm的体积随之变化
soundtouch->setRate(3.0); // rate,播放速率,1.0为正常速度;单设置这个时,除了影响播放速度,还会影响到音调
soundtouch->setPitch(0.5); // pitch,音调,1.0为正常音调;这个设置并不会影响到时长
AVFrame* frame = av_frame_alloc();
SwrContext* swr = NULL;
int gotframe = 0;
char outfile[512] = {0};
strcpy(outfile, filepath);
strcat(outfile + strlen(outfile), ".pcm");
FILE* file = fopen(outfile, "wb");
if (file) {
while (true) {
AVPacket packet;
av_init_packet(&packet);
status = av_read_frame(formatContext, &packet);
if (status < 0) {
if (status == AVERROR_EOF) {
av_log(NULL, AV_LOG_DEBUG, "read end for file\n");
break;
}
else {
av_packet_unref(&packet);
}
}
else {
if (packet.stream_index == audioindex) {
int srcCount = packet.size;
while (srcCount > 0) {
int decodedcount = avcodec_decode_audio4(codecContext, frame, &gotframe, &packet);
if (decodedcount < 0) {
av_log(NULL, AV_LOG_DEBUG, "decode failed, perhaps not enough data\n");
break;
}
if (gotframe > 0) {
// resample
int targetchannel = 2;
int targetsrate = 44100;
int targetfmt = AV_SAMPLE_FMT_S16;
bool needresample = false;
if (av_frame_get_channels(frame) != targetchannel || frame->sample_rate != targetsrate || frame->format != targetfmt) {
needresample = true;
}
if (needresample) {
if (swr == NULL) {
uint64_t in_channel_layout = av_get_default_channel_layout(av_frame_get_channels(frame));
uint64_t out_channel_layout = av_get_default_channel_layout(targetchannel);
int inSamplerate = frame->sample_rate;
swr = swr_alloc_set_opts(NULL,
out_channel_layout, (enum AVSampleFormat )AV_SAMPLE_FMT_S16, targetsrate,
in_channel_layout, (enum AVSampleFormat)frame->format, inSamplerate, 0, NULL);
int ret = swr_init(swr);
if (ret != 0) {
printf("swr_init failed: ret=%d\n", ret);
}
}
if (swr) {
if (frame->extended_data && frame->data[0] && frame->linesize[0] > 0) {
int out_size = av_samples_get_buffer_size(NULL, targetchannel, frame->nb_samples, (enum AVSampleFormat)targetfmt, 0);
void* out_buffer = av_malloc(out_size);
if (out_buffer) {
int convertSamples = swr_convert(swr, (uint8_t**)(&out_buffer), frame->nb_samples,
(const uint8_t**)frame->extended_data, frame->nb_samples);
int len = convertSamples * targetchannel * av_get_bytes_per_sample((enum AVSampleFormat)targetfmt);
int samplecount = convertSamples;
soundtouch->putSamples((SAMPLETYPE*)out_buffer, samplecount);
int bufsize = samplecount * frame->channels * sizeof(short);
unsigned char* buf = (unsigned char*)malloc(bufsize);
int gotsamplecount = soundtouch->receiveSamples((SAMPLETYPE*)buf, samplecount);
printf("soundtouch receiveSamples after resample:gotsamplecount=%d bufsize=%d sizeof(SAMPLETYPE)=%lu\n", gotsamplecount, bufsize, sizeof(SAMPLETYPE));
if (gotsamplecount) {
fwrite(buf, gotsamplecount * frame->channels * sizeof(short), 1, file);
}
free(buf);
av_free(out_buffer);
}
}
}
}
else {
int samplecount = frame->nb_samples;
soundtouch->putSamples((SAMPLETYPE*)frame->data[0], samplecount);
int bufsize = samplecount * frame->channels * sizeof(short);
unsigned char* buf = (unsigned char*)malloc(bufsize);
int gotsamplecount = soundtouch->receiveSamples((SAMPLETYPE*)buf, samplecount);
printf("soundtouch receiveSamples:gotsamplecount=%d bufsize=%d sizeof(SAMPLETYPE)=%lu\n", gotsamplecount, bufsize, sizeof(SAMPLETYPE));
if (gotsamplecount) {
fwrite(buf, gotsamplecount * frame->channels * sizeof(short), 1, file);
}
free(buf);
}
}
srcCount -= decodedcount;
}
}
}
av_packet_unref(&packet);
}
fclose(file);
}
av_frame_free(&frame);
delete soundtouch;
if (swr) {
swr_free(&swr);
}
}
avformat_free_context(formatContext);
}
// 保证这个ffmepg支持mp3编码即可(使用lamemp3),当然也可以编码成其它格式
// 我有多个不同特性的ffmpeg,这里指定一个能编码mp3的ffmpeg
const char* FFMPEGEXE = "/usr/local/Cellar/ffmpeg/2.6.2/bin/ffmpeg";
const int SAMPLE_RATE = 44100;
const int CHANNELS = 2;
const int BITRATE = 128;
const int BUF_LEN = 1024;
void encode(const char* srcfile, const char* outfile) {
char buf[BUF_LEN] = {0};
sprintf(buf, "%s -ar %d -ac %d -f s16le -i %s -ar %d -ac %d -b:a %dK -y %s", FFMPEGEXE, SAMPLE_RATE, CHANNELS, srcfile, SAMPLE_RATE, CHANNELS, BITRATE, outfile);
system(buf);
}
int main(int argc, const char *argv[])
{
const char filepath[] = "test2.mp3";
change_pcm_pitch(filepath); // xxx.xx.pcm create
encode("test2.mp3.pcm", "out.mp3");
return 0;
}
soundtouch,一个开源的音效处理项目(c++代码),可以用更改音频的音调、播放速率、节拍等特征。
上面的demo直接使用了soundtouch的源码来实现音效变化。
soundtouch初始化:
soundtouch作用于pcm:
需要注意,soundtouch并没有解码功能,它假设调用层已经有pcm数据。
对于复杂的音效处理,必定会更耗时,对于在线实时的播放,音效的性能是要关注的因素,避免音效太耗时而导致播放卡顿。
小白:我听了处理后的“李香兰”,表示很满意,记得来听我的演唱会。
花满楼:那你要关注我们,并及时在群里面分布信息了!
以上是关于写代码,让你的声音变得高亢的主要内容,如果未能解决你的问题,请参考以下文章
如何让你的代码变得更优雅?这些代码规范和技巧必须知道(进阶必备,建议收藏)
巧用Vscode编辑器,快速格式化代码,让你的代码变得整洁又美观
巧用Vscode编辑器,快速格式化代码,让你的代码变得整洁又美观