简体   繁体   中英

How can I perform conversion from float -> double -> float when processing an audio buffer in c++

I am currently developing an application where frames of audio samples are processed in the following callback.

void Eav07AudioProcessor::processBlock (AudioSampleBuffer& buffer)
{

    for (int channel = 0; channel < getNumInputChannels(); ++channel)
    {
        float* channelData = buffer.getSampleData (channel);        

        // ..do something to the data...
        DoSomeHeavyweightDSPon(&channelData[0]); // in the header, DoSomeHeavyweightDSPon(double data[somebignumber])
    }
}

The function that will sit in place of the gain process above expects channelData to be double precision. The channelData parameter is float precision. Do I need to somehow cast channelData from float to double and then from double to float after the processing or am I missing a trick.

If an explicit conversion is necessary, what is the most efficient way to do it considering that this method is called 100s of times per second.

Does the mentioned function take double or double* ? The latter case will always require copying all the channelData into a double buffer, and vice versa after the function ran. If you really want an efficient way, you will need to (copy and) change the problematic function to take float* intead of double*

if the function simply takes double , no explicit conversion is needed.

No, casting the float to double and back will not do what the gain()-function expects. The gain-function expects a pointer to an array of doubles and no amount of casting will do that.

The best thing you can do is replace the gain()-function. I would just use the "demo-code" you included (the inner for-loop).

If you have a requirement to call the gain(double*)-function you can do either:

  • create a second buffer with size: malloc(buffer.getNumSamples()*sizeof(double)) and copy them over by hand (memcpy doesnt work because it doesnt generate the four zero-bytes you need in between each float).

  • [hack]: just use the buffer you have but set every second float to 0, then sign extend the other float into this one. This effectively halves the number of samples you have but has very little overhead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM