播放amr格式音频
# 使用amrnb.js (opens new window)播放 amr 格式音频
- 对 amrnb.js 文件改造 最后一行增加
export { AMR }
1
- 引入使用
import { AMR } from 'filepath/amrbg.js'
import axios from 'axios'
// 获取二进制文件解码
const playAudio = (fileUrl) => {
axios.get(fileUrl, { responseType: 'blob' }).then(({ data: blob }) => {
var reader = new FileReader()
reader.onload = function (e) {
var samples = AMR.decode(new Uint8Array(e.target.result))
if (!samples) {
console.log('Failed to decode!')
return
}
playPcm(samples)
}
reader.readAsArrayBuffer(blob)
})
}
// 播放
const playPcm = (samples) => {
try {
var ctx = new AudioContext()
} catch (e) {
alert('您的浏览器暂不支持播放录音')
return
}
var src = ctx.createBufferSource()
var buffer = ctx.createBuffer(1, samples.length, 8000)
if (buffer.copyToChannel) {
buffer.copyToChannel(samples, 0, 0)
} else {
var channelBuffer = buffer.getChannelData(0)
channelBuffer.set(samples)
}
src.buffer = buffer
src.connect(ctx.destination)
src.start()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
上次更新: 2024/06/18, 13:22:15