Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สร้างเสียงแบบ Real-time ด้วย JavaScript/HTML5 Web Audio API

Web Audio API: ควบคุมเสียง สร้างเอฟเฟกต์ วิเคราะห์ความถี่

Web Audio API ใช้สร้างและประมวลผลเสียงในเบราว์เซอร์ได้โดยตรง

ตัวอย่างสร้างเสียง Sine Wave 500Hz เล่น 5 วินาที

// สร้าง AudioContext (รองรับทั้ง standard และ webkit)
var context = new (window.AudioContext || window.webkitAudioContext)();

// สร้าง Oscillator
var oscillator = context.createOscillator();
oscillator.type = 'sine'; // sine, square, sawtooth, triangle
oscillator.frequency.value = 500; // Hz

// เชื่อมต่อไปยัง output (ลำโพง)
oscillator.connect(context.destination);

// เริ่มเล่น และหยุดหลัง 5 วินาที
oscillator.start();
oscillator.stop(context.currentTime + 5);

สามารถขยายได้ เช่น เพิ่ม GainNode ควบคุมระดับเสียง หรือ Filter สร้างเอฟเฟกต์