How to Make and Play A Procedurally Generated Chirp Sound

后端 未结 2 462
半阙折子戏
半阙折子戏 2021-02-10 07:36

My goal is to create a \"Chirper\" class. A chirper should be able to emit a procedurally generated chirp sound. The specific idea is that the chirp must be procedurally generat

2条回答
  •  后悔当初
    2021-02-10 08:25

    You can do it with a sine wave as you said, which you would define using the sin functions. Create a buffer as long as you want the sound in samples, such as:

    // 1 second chirp
    float samples[44100];
    

    Then pick a start frequency and end frequency, which you probably want the start to be higher than the end, something like:

    float startFreq = 1400;
    float endFreq = 1100;
    
    float thisFreq;
    int x;
    for(x = 0; x < 44100; x++)
    {
        float lerp = float(float(x) / 44100.0);
    
        thisFreq = (lerp * endFreq) + ((1 - lerp) * startFreq);
        samples[x] = sin(thisFreq * x);
    }
    

    Something like that, anyway.

    And if you want a buzz or another sound, use different waveforms - create them to work very similarly to sin and you can use them interchangably. That way you could create saw() sqr() tri(), and you could do things like combine them to form more complex or varied sounds

    ========================

    Edit -

    If you want to play you should be able to do something along these lines using OpenAL. The important thing is to use OpenAL or a similar iOS API to play the raw buffer.

        alGenBuffers (1, &buffer); 
        alBufferData (buffer, AL_FORMAT_MONO16, buf, size, 8000); 
        alGenSources (1, &source); 
    
        ALint state; 
    
        // attach buffer and play 
        alSourcei (source, AL_BUFFER, buffer); 
        alSourcePlay (source); 
    
        do 
        { 
            wait (200); 
            alGetSourcei (source, AL_SOURCE_STATE, &state); 
        } 
        while ((state == AL_PLAYING) && play); 
    
        alSourceStop(source); 
        alDeleteSources (1, &source); 
    
        delete (buf) 
    } 
    

提交回复
热议问题