【问题标题】:javascript generate square wave soundjavascript生成方波声音
【发布时间】:2015-09-17 12:21:46
【问题描述】:

我想使用信号“1 0 0 0”生成方波声音。每个代码 (0,1) 都有一个如picture 所示的模式。

例如,代码 1 将产生 500µs 的声音,然后停止 1000µs。信号应该从零到最大正幅度,并且不会有任何负幅度。声音的频率是 10KHz。

基本上我需要从移动设备(iPhone、Android 和 Windows phone 8)生成这种声音。我正在使用 Cordova 框架。有什么建议吗?

【问题讨论】:

    标签: javascript android cordova audio windows-phone-8


    【解决方案1】:

    检查一下

    var frequency = 10000;
    var data = {
        1: {duration:500, sleep:1000},
        0: {duration:500, sleep:500}
    }
    var audio = new window.webkitAudioContext();
    
    
    //function creates an Oscillator. In this code we are creating an Oscillator for every tune, which help you control the gain. 
    //If you want, you can try creating the Oscillator once and stopping/starting it as you wish.
    function createOscillator(freq, duration) {
        var attack = 10, //duration it will take to increase volume full sound volume, makes it more natural
            gain = audio.createGain(),
            osc = audio.createOscillator();
    
        gain.connect(audio.destination);
        gain.gain.setValueAtTime(0, audio.currentTime); //change to "1" if you're not fadding in/out
        gain.gain.linearRampToValueAtTime(1, audio.currentTime + attack / 1000); //remove if you don't want to fade in
        gain.gain.linearRampToValueAtTime(0, audio.currentTime + duration / 1000); //remove if you don't want to fade out
    
        osc.frequency.value = freq;
        osc.type = "square";
        osc.connect(gain);
        osc.start(0);
    
    
        setTimeout(function() {
            osc.stop(0);
            osc.disconnect(gain);
            gain.disconnect(audio.destination);
        }, duration)
    }
    
    function play() {
        //your pattern
        var song = [1,0,1,1];       
    
        timeForNext = 0;
        for (i=0;i<song.length;i++){            
            duration = data[song[i]].duration;
            //use timeout to delay next tune sound
            window.setTimeout(function(){
                createOscillator(frequency, duration);
            },timeForNext);         
            timeForNext+=data[song[i]].sleep;       
        }
    }
    
    //play the music
    play();
    

    这个链接有一些很好的信息http://www.bit-101.com/blog/?p=3896 不久前我用它用 Cordova 创建了一个钢琴应用程序。不过还没有发布。

    【讨论】:

    • 非常感谢您的帮助。我认为不是“timeForNext+=data[song[i]].sleep;”,而是“timeForNext = timeForNext + data[signal[i]].duration + data[signal[i]].sleep;”以获得适当的睡眠延迟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    相关资源
    最近更新 更多