使用Howler.js在JavaScript中处理音频
时间:2020-02-23 14:33:52 来源:igfitidea点击:
在本教程中,我们将学习Howler.js,它使在所有平台上使用JavaScript进行音频操作变得轻松可靠。
单击此处访问Howler.js GitHub存储库。 https://github.com/goldfire/howler.js
安装
如果安装了Node和NPM,则在终端中使用以下命令将咆哮声作为项目中的依赖项。
npm install howler --save
Or, get the latest release from Howeler.js GitHub repository.
Or, get it from CDN like cdnjs and jsDelivr.
步骤1:包含脚本
在页面中包含howler.js脚本。
<script src="path/to/howler.js"></script>
步骤2:实例化和配置咆哮
现在,是时候实例化Howler并将其配置为播放音频文件了。
在下面的示例中,我们包括一个音频文件audio.mp3并将音量值设置为0到1。
然后,我们使用play()方法播放音频。
var sound = new Howl({
src: ['path/to/audio.mp3'],
volume: 0.8
});
sound.play();
例
播放暂停停止Vol + Vol
音频法庭:sample-videos.com
播放按钮运行play()方法,该方法开始播放声音。
暂停按钮运行pause()方法,该方法暂停声音的播放。
"停止"按钮运行stop()方法,该方法将停止播放声音并将搜索重置为0。
因此,如果播放音频5秒钟并单击"停止"按钮,则搜索将重置为0秒,当从0开始再次播放音频。
Vol +按钮增大音量,而Vol-按钮减小音量。
HTML
<button id='howler-play'>Play</button> <button id='howler-pause'>Pause</button> <button id='howler-stop'>Stop</button> <button id='howler-volup'>Vol+</button> <button id='howler-voldown'>Vol-</button>
JavaScript
注意!在以下示例中使用jQuery。
$(function(){
var howler_example = new Howl({
src: ['/audio/sample/SampleAudio_0.4mb.mp3'],
volume: 0.5
});
$("#howler-play").on("click", function(){
howler_example.play();
});
$("#howler-pause").on("click", function(){
howler_example.pause();
});
$("#howler-stop").on("click", function(){
howler_example.stop();
});
$("#howler-volup").on("click", function(){
var vol = howler_example.volume();
vol += 0.1;
if (vol > 1) {
vol = 1;
}
howler_example.volume(vol);
});
$("#howler-voldown").on("click", function(){
var vol = howler_example.volume();
vol -= 0.1;
if (vol < 0) {
vol = 0;
}
howler_example.volume(vol);
});
});

