由于我是 openAL 的新手,我无法同时显示和播放声音 这个程序。有人可以帮我解决这个问题吗。
代码在同一个 .c 文件中包含 openAL 和 openGL 文件。
谢谢。
#include <AL/al.h>
//#include <AL/alc.h>
#include <AL/alut.h>
#include <stdio.h>
#include <GL/gl.h>
#include<GL/glu.h>
#include <GL/glut.h>
//gcc -lopenal -lalut -lGL -lGLU -lglut filename.c -lm
#define FILENAME "clap.wav"
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
glClearColor(0,0,0,1);
ALuint buffer, source;
ALuint state;
// Load pcm data into buffer
buffer = alutCreateBufferFromFile(FILENAME);
// Create sound source (use buffer to fill source)
alGenSources(1, &source);
alSourcei(source, AL_BUFFER, buffer);
//glutPostRedisplay();
// Play
alSourcePlay(source);
// Wait for the song to complete
do {
alGetSourcei(source, AL_SOURCE_STATE, &state);
} while (state == AL_PLAYING);
// Clean up sources and buffers
alDeleteSources(1, &source);
alDeleteBuffers(1, &buffer);
// Exit everything
alutExit();
glFlush ();
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
// Initialize the environment
alutInit(&argc,argv);
// Capture errors
alGetError();
glutInitWindowPosition (100, 100);
glutCreateWindow ("Greeting");
//init ();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
最佳答案
您必须分开加载声音、播放声音和清除缓冲区。 但你目前的问题是,你在显示功能中循环,直到声音播放完毕!因此,在那之前您当然不会看到任何渲染。
此外,您不应该在每次调用 display 函数时加载/删除声音 - 只需加载一次:然后在 display() 函数中播放它。 如果你完成了声音,你可以删除它。但请记住,您必须再次加载它才能再次播放 - 所以您可能想将它留在内存中并在程序终止时将其删除。
但是这个片段会加载声音,播放一次(继续渲染)然后删除它。
#include <AL/al.h>
//#include <AL/alc.h>
#include <AL/alut.h>
#include <stdio.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
//gcc -lopenal -lalut -lGL -lGLU -lglut filename.c -lm
#define FILENAME "clap.wav"
ALuint buffer, source;
void loadSound(){
// Load pcm data into buffer
buffer = alutCreateBufferFromFile(FILENAME);
// Create sound source (use buffer to fill source)
alGenSources(1, &source);
alSourcei(source, AL_BUFFER, buffer);
}
void cleanUpSound(){
// Clean up sources and buffers
alDeleteSources(1, &source);
alDeleteBuffers(1, &buffer);
}
void playSound(){
alSourcePlay(source);
}
void display(void){
static int shouldPlaySound = 1;
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
glClearColor(0,0,0,1);
if(shouldPlaySound){
loadSound();
playSound();
shouldPlaySound = 0;
}else{
ALuint state;
alGetSourcei(source, AL_SOURCE_STATE, &state);
if(state != AL_PLAYING){
cleanUpSound();
}
}
glFlush ();
}
int main(int argc, char **argv){
glutInit(&argc,argv);
// Initialize the environment
alutInit(&argc,argv);
// Capture errors
alGetError();
glutInitWindowPosition (100, 100);
glutCreateWindow ("Greeting");
//init ();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
关于c - OpenAL 阻止 OpenGL 显示图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20281168/