JS音频倍速采用音调保持不变实例页面

回到相关文章 »

效果:

原始音频

选择播放速率:

转换音频预览

代码:

HTML代码:
<h4>原始音频</h4>
<p>
    <audio src="/study/201812/audio/zxx-comic-01.mp3" controls></audio>
</p>

<p>选择播放速率:</p>
<p>
    <label><input type="radio" name="rate" value="0.5">0.5倍速</label>
    <label><input type="radio" name="rate" value="1" checked>1倍速</label>
    <label><input type="radio" name="rate" value="1.5">1.5倍速</label>
    <label><input type="radio" name="rate" value="2">2倍速</label>
</p>

<p>
    <button class="button">开始转换</button>
</p>

<h4>转换音频预览</h4>
<p>
    <audio id="audio" controls></audio>
</p>
JS代码:
<script type="module">
    import bufferToWav from './buffer2wav.js';
    import stretch from './audioStretch.js';

    // 原始音频的AudioBuffer
    let originAudioBuffer;
    
    const eleAudio = document.querySelector('audio');

    // 获取原始音频的audiobuffer数据
    fetch(eleAudio.src)
        .then(response => response.arrayBuffer())
        .then(arrayBuffer => new AudioContext().decodeAudioData(arrayBuffer))
        .then(audioBuffer => {
            // 获取原始音频的采样率
            originAudioBuffer = audioBuffer;
        });

    // 点击按钮
    document.querySelector('button').onclick = () => {
        // 获取选中的倍速
        const rate = document.querySelector('input[name="rate"]:checked').value * 1;

        // 创建新的Audio上下文
        const audioContent = new AudioContext();
        // 倍速变化,返回新的AudioBuffer
        const audioBuffer = stretch(audioContent, originAudioBuffer, 1 / rate, {
            seqSize: originAudioBuffer.sampleRate / 10,
            overlap: originAudioBuffer.sampleRate / 100
        });

        // 播放合成的新音频
        const audio = document.querySelector('#audio');
        const blob = bufferToWav(audioBuffer, audioBuffer.length);
        const audioURL = URL.createObjectURL(blob, { type: 'audio/wav' });
        audio.src = audioURL;
    };
</script>