JavaScript 中可以通过 Audio 对象的 volume 属性来控制音频音量. volume 属性设置或返回音频的音量, 从 0.0(静音) 到 1.0(最大声).
JavaScript 控制音频音量实现代码如下:
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>
- Document
- </title>
- <script src="https://cdn.bootCSS.com/jquery/3.2.1/jquery.min.js">
- </script>
- </head>
- <body>
- <div>
- <audio id="audio" controls src="http://m10.music.126.net/20170719161110/
- 02863ba74071062bce6dd56bf5907797/ymusic/450e/0b69/b118/e3a5be41869989ca3723c8cca2bf82ad.mp3">
- </audio>
- <button id="down">
- ↓
- </button>
- <button id="up">
- ↑
- </button>
- </div>
- </body>
- <script>
- $(function() {
- let vol = $('#audio')[0].volume;
- $('#audio').on('canplay',
- function() {
- this.play()
- });
- $('#down').click(function() {
- console.log(vol) vol = vol > 0 ? (vol * 10 - 1) / 10 : 0;
- $('#audio')[0].volume = vol;
- }) $('#up').click(function() {
- console.log(vol) vol = vol < 1 ? (vol * 10 + 1) / 10 : 1;
- $('#audio')[0].volume = vol;
- })
- })
- </script>
- </HTML>
Audio 对象
Audio 对象代表着 HTML <audio> 元素.
访问 Audio 对象
你可以使用 getElementById() 来访问 <audio> 元素:
var x = document.getElementById("myAudio");
创建 Audio 对象
你可以使用 document.createElement() 方法创建 <audio> 元素:
var x = document.createElement("AUDIO");
Audio volume 属性
volume 属性设置或返回音频的音量, 从 0.0 (静音) 到 1.0 (最大声).
语法
返回 volume 属性:
audioObject.volume
设置 volume 属性:
audioObject.volume=number
属性值:
volumevalue: 规定音频的当前音量. 必须是介于 0.0 与 1.0 之间的数字.
来源: http://www.css88.com/qa/javascript/11420.html