2017-02-24 90 views
1

我的目標是將發動機的RPM與聲音的音高相關聯。我正在使用SDL作爲我的音頻後端。SDL Audio Pitch - 播放速率

所以我的想法是比平時更快地從波形緩衝區採樣。因此,通過跟蹤和錯誤,我現在能夠「一步一步」調整發動機聲音。

問題#1

如果我從改變這一部分:

audioBuff += 1 + pitch * 2; 

audioBuff += 2 

我得到的只是噪音。爲什麼?這是否與立體聲頻道有關?

問題2

我怎樣才能讓這個線性間距?目前這是一個「跨步」的​​音調。

下面是完整的代碼:

#include "SDL2/SDL.h" 
#include <iostream> 



void audioCallback(void* userdata, Uint8 *stream, int len); 

Uint8 *audioBuff = nullptr; 
Uint8 *audioBuffEnd = nullptr; 
Uint32 audioLen = 0; 
bool quit = false; 
Uint16 pitch = 0; 

int main() 
{ 
    if(SDL_Init(SDL_INIT_AUDIO) < 0) 
     return -1; 

    Uint32 wavLen = 0; 
    Uint8 *wavBuff = nullptr; 
    SDL_AudioSpec wavSpec; 

    if(SDL_LoadWAV("test.wav", &wavSpec, &wavBuff, &wavLen) == nullptr) 
    { 
     return 1; 
    } 
    wavSpec.callback = audioCallback; 
    wavSpec.userdata = nullptr; 
    wavSpec.format = AUDIO_S16; 
    wavSpec.samples = 2048; 
    audioBuff = wavBuff; 
    audioBuffEnd = &wavBuff[wavLen]; 
    audioLen = wavLen; 

    if(SDL_OpenAudio(&wavSpec, NULL) < 0) 
    { 
     fprintf(stderr, "Could not open audio: %s\n", SDL_GetError()); 
     return 1; 
    } 

    SDL_PauseAudio(0); 
    while(!quit) 
    { 
     SDL_Delay(500); 
     pitch ++; 

    } 

    SDL_CloseAudio(); 
    SDL_FreeWAV(wavBuff); 
    return 0; 
} 


Uint32 sampleIndex = 0; 
void audioCallback(void* userdata, Uint8 *stream, int len) 
{ 
    Uint32 length = (Uint32)len; 
    length = (length > audioLen ? audioLen : length); 

    for(Uint32 i = 0; i < length; i++) 
    { 
     if(audioBuff > audioBuffEnd) 
     { 
      quit = true; 
      return; 
     } 
     // why pitch * 2? 
     // how to get a smooth pitch? 
     stream[i] = audioBuff[0]; 
     audioBuff += 1 + pitch * 2; 
     fprintf(stdout, "pitch: %u\n", pitch); 
    } 
} 
+1

你是什麼意思的「線性瀝青」? – 1201ProgramAlarm

+0

我自己也在問同一個問題@ 1201ProgramAlarm – Hydren

+0

可以將音調應用於SDL_mixer的Mix_Chunk嗎? – Hydren

回答

1

你設置音頻格式AUDIO_S16,這是「符號16位小端的樣本」。每個採樣是兩個字節,第一個字節是LSB。當您讀取audioCallback中的數據時,您將以字節(8位)的形式讀取數據,然後將這些字節傳回給期望16位的數據。由於這個原因,你會聽到噪音,當你使用audioBuff +=2;時,你總是讀取音頻採樣的LSB,當使用這種方式時,它本質上是噪聲。

您應該一致地使用16位或8位樣本。

+0

好的,謝謝。這是我的回調函數現在的樣子: 'void audioCallback(void * userdata,Uint8 * stream,int len) { Uint32 length =(Uint32)len;如果(audioBuff> audioBuffEnd) { quit = true;(uint32i = 0; i audioBuffEnd) { return; } stream [i] = audioBuff [0]; i ++; stream [i] = audioBuff [1]; audioBuff + = 2 * pitch; } }' – MadSystem