audio

183 阅读2分钟

1. 创建一个audio元素

  • 使用 html 标签创建
<audio src="" ></audio>
  • 使用 js 方式 创建
// dom api
const audioByDom = document.createElement("audio")
// class
const audioByClass = new Audio()

2. 显示 audio 元素 的 原生音频控件

  • 添加了 controls 会展示音频控件

1716277082082.png

  • 创建的 dom 设置 controls 属性
audio.setAttribute("controls", true)
  • 如果要删除布尔属性 类似 controls
// 错误示范
doms.audio.setAttribute("controls", "") // 这里赋值 "" null undefined 都会出现控件
// 正确示范
doms.audio.removeAttribute("controls")

3. 监视播放进度条的变化

audio.addEventListener("timeupdate", (event) => {
  console.log(event, `---------------->event`)
})

4. audio 加载多个 资源

1696130920961.png

1696130906301.png

  • 通过 js 的 方式 添加 音频
const audio = new Audio()
audio.setAttribute("controls", undefined) // 这里赋值 "" null undefined 都会出现控件const source = document.createElement("source")
source.setAttribute("src", "./sound.mp3")
​
audio.appendChild(doms.source)

4. audio 操作

4.1 播放

doms.payBtn.addEventListener('click', () => {
  doms.audio.play()
})

4.2 暂停

doms.stopBtn.addEventListener('click', () => {
  doms.audio.pause()
})

4.3 改变播放时间点

// 快进
doms.fastBtn.addEventListener('click', () => {
  doms.audio.currentTime += 10
})

4.4 静音

property(对象属性) 和 Attribute(标签属性) 是不同的

blog.csdn.net/rudy_zhou/a…

解析创建后的这个DOM节点对象property是这个对象的属性,而attribute是这个对象的attributes这个对象的属性(简单讲就是这样 domObj.attibutes.attribute )。

DOM节点对象上的type属性(property)是映射 type的属性(attribute),获取property读取的是attribute值,并且设置property写入的是attribute值。type不是纯粹的映射属性,因为它的值只能为 已知值 (例如:text,submit,button,checkbox等等)。以下可以看到,设置type为未知值 时 property始终为text。

var inputDom = document.querySelector('#inputId')
console.log(inputDom.getAttribute('id'))
console.log(inputDom.id)
// "inputId"
// "inputId"

inputDom.setAttribute('id','inputId2')
console.log(inputDom.getAttribute('id'))
console.log(inputDom.id)
// "inputId2"
// "inputId2"

inputDom.id = 'inputId'
console.log(inputDom.getAttribute('id'))
console.log(inputDom.id)
// "inputId"
// "inputId"

value属性(property)不是完全映射value属性(attribute)。 初始状态value属性(property)映射的value属性(attribute), 当用户手动更改输入框的内容时 , value属性(property)将更改为用户输入的信息。

var inputDom = document.querySelector('#inputId')
console.log(inputDom.getAttribute('value'))
console.log(inputDom.value)
// name
// name

inputDom.setAttribute('value','007')
console.log(inputDom.getAttribute('value'))
console.log(inputDom.value)
// 007
// 007

inputDom.value = '008'
console.log(inputDom.getAttribute('value'))
console.log(inputDom.value)
// 007
// 008
  • muted属性类似于<input>的value属性,如果他在元素初始化时是内联的,那么属性值将作为初始值;但是如果在一开始并没有内联,只是后续更改了attribute 值,那么将不会起任何效果,正确的做法是设置相对应的property 值。
  • 所以,通过js创建的元素一开始没有内联,在需要直接赋值
// doms.audio.setAttribute("muted", "muted") 不生效
doms.audio.muted = true

4.5 设置 音量

doms.volume.addEventListener("keyup", (e) => {
  if (e.key !== 'Enter') return
  if (e.target.value === 0) doms.audio.muted = true
  doms.audio.muted = false
  doms.audio.volume = e.target.value
})