Algorithm to mix sound

后端 未结 20 2053
囚心锁ツ
囚心锁ツ 2020-11-29 16:55

I have two raw sound streams that I need to add together. For the purposes of this question, we can assume they are the same bitrate and bit depth (say 16 bit sample, 44.1k

20条回答
  •  抹茶落季
    2020-11-29 17:15

    I found a new way to add samples in a way in which they can never exceed a given range. The basic Idea is to convert values in a range between -1 to 1 to a range between approximately -Infinity to +Infinity, add everything together and reverse the initial transformation. I came up with the following formulas for this:

    f(x)=-\frac{x}{|x|-1}

    f'(x)=\frac{x}{|x|+1}

    o=f'(\sum f(s))

    I tried it out and it does work, but for multiple loud sounds the resulting audio sounds worse than just adding the samples together and clipping every value which is too big. I used the following code to test this:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    // fabs wasn't accurate enough
    long double ldabs(long double x){
      return x < 0 ? -x : x;
    }
    
    // -Inf 1. )
        ret = 1.;
      return ret;
    }
    
    // -1<=input<=+1, -Inf 1. )
        sample = 1.;
      if( sample < -1. )
        sample = -1.;
      long double res = -( sample / ( ldabs(sample) - 1. ) );
      // sample was too close to 1 or -1, return largest long double
      if( isinf(res) )
        return sample < 0 ? -LDBL_MAX : LDBL_MAX;
      return res;
    }
    
    // -1 max_read )
              max_read = read_count;
          }
          long double insamples[argc-2];
          for( size_t j=0; j

提交回复
热议问题