采样率转换函数中的分段错误

时间:2014-06-17 16:03:21

标签: c audio ffmpeg signal-processing libavcodec

playmp3()使用libmpg123

if (isPaused==0 && mpg123_read(mh, buffer, buffer_size, &done) == MPG123_OK)
{
    char * resBuffer=&buffer[0]; //22100=0,5s
    buffer = resample(resBuffer,22100,22100);
    if((ao_play(dev, (char*)buffer, done)==0)){
        return 1;
}

resample()使用ffmpeg的avcodec

#define LENGTH_MS 500       // how many milliseconds of speech to store
#define RATE 44100      // the sampling rate (input)
#define FORMAT PA_SAMPLE_S16NE  // sample size: 8 or 16 bits
#define CHANNELS 2      // 1 = mono 2 = stereo

struct AVResampleContext* audio_cntx = 0;

char * resample(char in_buffer[(LENGTH_MS*RATE*16*CHANNELS)/8000],int out_rate,int nsamples)
{
    char out_buffer[ sizeof( in_buffer ) * 4];
    audio_cntx = av_resample_init( out_rate, //out rate
        RATE, //in rate
        16, //filter length
        10, //phase count
        0, //linear FIR filter
        1.0 ); //cutoff frequency
    assert( audio_cntx && "Failed to create resampling context!");
    int samples_consumed;
    int samples_output = av_resample( audio_cntx, //resample context
        (short*)out_buffer, //buffout
        (short*)in_buffer,  //buffin
        &samples_consumed,  //&consumed
        nsamples,       //nb_samples
        sizeof(out_buffer)/2,//lenout
        0);//is_last
    assert( samples_output > 0 && "Error calling av_resample()!" );
    av_resample_close( audio_cntx );
    //*resample = malloc(sizeof(out_buffer));
    return &out_buffer[0];  
}

当我运行此代码时,我得到 3393分段错误(创建核心转储)。为什么呢?

例如,使用指针是否正确? 和歌曲的0.5秒包含的样本是22100?

1 个答案:

答案 0 :(得分:1)

我有两个问题,我可以立即看到。这些都是菜鸟问题,但每个人都至少做过一次,所以不用担心!

检查sizeof(in_buffer)是否为您提供所需缓冲区的大小((LENGTH_MS * RATE * 16 * CHANNELS)/ 8000)或指针的大小(根据您的大小为2,4或8) system。)在堆栈上的数组上使用sizeof可以得到它的总大小,因为没有指针只有一个缓冲区。即使在param列表中使用[],参数列表上的数组大小也会显示指针的大小,因为只有指针。

此外,返回基于堆栈的缓冲区是未定义的(即会崩溃),因为堆栈会在下一个函数调用中重用:

return &out_buffer[0]; 

不要那样做。传入已由调用者分配的out缓冲区。

相关问题