Skip to content

Instantly share code, notes, and snippets.

@takeshich
Created December 21, 2017 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takeshich/926e1829b65c771d1f800f97c94bfd10 to your computer and use it in GitHub Desktop.
Save takeshich/926e1829b65c771d1f800f97c94bfd10 to your computer and use it in GitHub Desktop.
OpenALでの使用例
//略
IntPtr device;
OpenTK.ContextHandle context;
private void button1_Click(object sender, EventArgs e)
{
if (_tokenSource == null) _tokenSource = new CancellationTokenSource();
var token = _tokenSource.Token;
//初期化
device = Alc.OpenDevice(null);
context = Alc.CreateContext(device, (int[])null);
Alc.MakeContextCurrent(context);
string filename = Path.Combine("wav", "walk-fallen-leaves_mono.wav");
//リッスンポジションなどの設定
float[] ListenOri = { 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f }; // look.x.y.z / up.x.y.z
AL.Listener(ALListener3f.Position, 0.0f, 1.5f, 0.0f);
AL.Listener(ALListener3f.Velocity, 0.0f, 0.0f, 0.0f);
AL.Listener(ALListenerfv.Orientation, ref ListenOri);
AL.Listener(ALListenerf.Gain, 1.0f);
//buffer とsourceのひもづけ
var buffer = createBuffer(filename);
var source = AL.GenSource();
AL.BindBufferToSource(source, buffer);
//ソースの設定
AL.Source(source[0], ALSourceb.Looping, true); // 繰り返し
AL.Source(source[0], ALSourcef.Pitch, 1.0f); //
AL.Source(source[0], ALSourcef.Gain, 1.0f); // 音量
AL.Source(source[0], ALSource3f.Position, 0.0f, 0.0f, 0.0f);
AL.SourcePlay(source);
//1周16秒で円を描きたい 2πr
//2*3*3 18m
//を16秒は妥当かな?
int i = 0;
int n = 160;
double rate = 0.0d;
double r = 2.0d;
float x;
float z;
Task.Factory.StartNew(() =>
{
while (true)
{
//円
//座標を計算
rate = (double)i / (double)n;
x = (float)(r * Math.Cos(2.0 * Math.PI * rate));
z = (float)(r * Math.Sin(2.0 * Math.PI * rate));
AL.Source(source, ALSource3f.Position, x, 0.0f, z);
System.Threading.Thread.Sleep(100);
i++;
//Console.WriteLine("x:{0},z:{1},i:{2},rate:{3:000.0000}", x, z, i, rate);
if (i == n)
{
i = 0;
}
if (token.IsCancellationRequested)
{
// TODO:キャンセル処理
break;
}
}
}, token).ContinueWith(t =>
{
// TODO:あとしまつ
_tokenSource.Dispose();
_tokenSource = null;
// TODO:キャンセルされたときの処理
AL.SourcePause(source);
//使わなくなったデータをクリーンアップ
AL.DeleteSource(source);
AL.DeleteBuffer(buffer);
Alc.MakeContextCurrent(OpenTK.ContextHandle.Zero);
Alc.DestroyContext(context);
Alc.CloseDevice(device);
});
}
private static int createBuffer(string filename)
{
int channels, bits_per_sample, sample_rate;
var buffer = AL.GenBuffer();
var bufferData = new byte[bufferFrequency * bufferSeconds];
var sound_data = LoadWave(File.Open(filename, FileMode.Open), out channels, out bits_per_sample, out sample_rate);
AL.BufferData(buffer, GetSoundFormat(channels, bits_per_sample), sound_data, sound_data.Length, sample_rate);
return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment