質問編集履歴

1

編集

2022/10/26 11:20

投稿

aaaa____
aaaa____

スコア26

test CHANGED
File without changes
test CHANGED
@@ -188,4 +188,77 @@
188
188
  エラーの対処法
189
189
 
190
190
 
191
-
191
+ ### 追記
192
+ intとなってしまっていて計算結果が0になってしまうところをfloat64に直しました.
193
+ またgainの引数の取り方を修正しました.
194
+ この状態でビルドして実行し.ブラウザに行くと,ボタンを押すと,ランダムな1音がずっと残る状態になりました.
195
+
196
+ ```go
197
+ package main
198
+
199
+ import (
200
+ "syscall/js"
201
+ "time"
202
+ "math/rand"
203
+ "math"
204
+ )
205
+
206
+ func num_to_freq (notenum int) float64{
207
+ // 基準音から何音高い/低いかを計算する
208
+ from_concert_a := notenum - 69
209
+ // 周波数を実際に計算する
210
+ // 十二平均律では2音の最小の周波数差は`2^(1/12)`となる
211
+ freq := math.Pow(2, float64(from_concert_a) / 12) * 440;
212
+ return freq;
213
+ }
214
+
215
+ func main() {
216
+ // グローバルオブジェクト(window)を取得します
217
+ window := js.Global()
218
+
219
+ // document オブジェクトを取得します
220
+ document := window.Get("document")
221
+
222
+ // bodyを取得します
223
+ body := document.Get("body")
224
+
225
+ // ボタンのDOMを作成し、Clickイベントを設定します
226
+ btn := document.Call("createElement", "button")
227
+ btn.Set("textContent", "music start!")
228
+ btn.Call("addEventListener", "click", js.FuncOf(func(js.Value, []js.Value) interface{} {
229
+ ctx := js.Global().Get("AudioContext").New()
230
+ osc := js.Global().Get("OscillatorNode").New(ctx)
231
+ gain := js.Global().Get("GainNode").New(ctx)
232
+ gain.Get("gain").Set("value", 0)
233
+
234
+ bpm := 120.0
235
+ note_length := 60.0 / bpm
236
+
237
+ osc.Call("connect", gain)
238
+ gain.Call("connect", ctx.Get("destination"))
239
+ osc.Call("start")
240
+
241
+ rand.Seed(time.Now().UnixNano())
242
+
243
+ for n := 0; n < 120; n++{
244
+ randNote := rand.Intn(20) + 55
245
+ start_t := float64(n) * note_length
246
+ end_t := start_t + 0.5
247
+ gain.Get("gain").Call("setValueAtTime", 0.3, ctx.Get("currentTime").Float()+start_t)
248
+ gain.Get("gain").Call("setValueAtTime", 0., ctx.Get("currentTime").Float()+end_t)
249
+ osc.Get("frequency").Set("value", num_to_freq(randNote))
250
+ }
251
+ osc.Set("type", "sawtooth")
252
+ return nil
253
+ }))
254
+ // ボタンをbodyに追加します
255
+ body.Call("appendChild", btn)
256
+
257
+ // プログラムが終了しないように待機します
258
+ select {}
259
+
260
+ }
261
+
262
+ ```
263
+
264
+