2011-04-21 74 views
4

我想把電路連接到我的電腦,它使用音頻輸出作爲交流電流,通過某些頻率,然後將其整流爲幾個LED,所以如果我編寫一個程序讓您創建特定的模式和組合的LED被點亮,它會輸出特定的頻率聲音。C++特定的聲音輸出?

如何使用C++播放特定頻率的聲音?

可能嗎?

+1

你在使用什麼操作系統?任何特定的庫/框架? – Gabe 2011-04-21 01:45:46

+1

完全取決於設備和設備驅動程序。 – 2011-04-21 01:49:23

+0

已關閉。如果沒有James和Gabe的查詢答案,我們無法爲您提供有意義的答案。請注意,即使有了這些信息,您仍然應該自己研究這個問題,而不要在信息卡住之前要求提供信息。儘管如果你的問題是關於你的電路的具體細節的話,你也會面臨被封閉的風險。在這種情況下,我建議在討論板上尋求關於特定電路的幫助。 – Brian 2011-04-21 17:43:04

回答

1

你可以用OpenAL來做到這一點。

您需要生成一個包含PCM編碼數據的數組,以表示所需的輸出,然後以所需的採樣頻率和格式在陣列上調用alBufferData()。請參閱OpenAL Programmers Guide的第21頁,瞭解alBufferData()函數所需的格式。

例如,以下代碼播放100hz音調。

#include <iostream> 

#include <cmath> 

#include <al.h> 
#include <alc.h> 
#include <AL/alut.h> 

#pragma comment(lib, "OpenAL32.lib") 
#pragma comment(lib, "alut.lib") 

int main(int argc, char** argv) 
{ 
    alutInit(&argc, argv); 
    alGetError(); 

    ALuint buffer; 
    alGenBuffers(1, &buffer); 

    { 
    // Creating a buffer that hold about 1.5 seconds of audio data. 
    char data[32 * 1024]; 

    for (int i = 0; i < 32 * 1024; ++i) 
    { 
     // get a value in the interval [0, 1) over the length of a second 
     float intervalPerSecond = static_cast<float>(i % 22050)/22050.0f; 

     // increase the frequency to 100hz 
     float intervalPerHundreth = fmod(intervalPerSecond * 100.0f, 1.0f); 

     // translate to the interval [0, 2PI) 
     float x = intervalPerHundreth * 2 * 3.14159f; 

     // and then convert back to the interval [0, 255] for our amplitude data. 
     data[i] = static_cast<char>((sin(x) + 1.0f)/2.0f * 255.0f); 
    } 

    alBufferData(buffer, AL_FORMAT_MONO8, data, 32 * 1024, 22050); 
    } 

    ALuint source; 
    alGenSources(1, &source); 

    alSourcei(source, AL_BUFFER, buffer); 

    alSourcePlay(source); 

    system("pause"); 

    alSourceStop(source); 

    alDeleteSources(1, &source); 

    alDeleteBuffers(1, &buffer); 

    alutExit(); 

    return 0; 
}