引用的js文件是
AudioAPI.js
,代码如下:
const navigator = window.navigator
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia
const AudioContext = window.AudioContext ||
window.webkitAudioContext
const isSupport = !!(navigator.getUserMedia && AudioContext)
const context = isSupport && new AudioContext()
var AudioApi = window.AudioApi = function(){
}
function start(){
// https://developer.mozilla.org/zh-CN/docs/Web/API/AudioContext AudioContent API
return new Promise((resolve, reject) => {
navigator.getUserMedia({audio: true}, stream => { // 申请浏览器麦克风权限
const source = context.createMediaStreamSource(stream)
// 该对象可以获得声音的频率数据 https://developer.mozilla.org/zh-CN/docs/Web/API/AudioContext/createAnalyser
const analyser = context.createAnalyser()
source.connect(analyser)
analyser.fftSize = 2048
resolve(analyser)
}, () => {
reject()
})
})
}
}
function getVoiceSize(analyser){
const dataArray = new Uint8Array(analyser.frequencyBinCount)
// 这里会获得一个数组,数字的下标表示频率,数组的值表示频率波大小
// 通过对这些值的一个简单累加,就可以得到一个数字,用于游戏中表示声音的大小
analyser.getByteFrequencyData(dataArray)
const data = dataArray.slice(100, 1000) // 只获得 100 - 1000Hz 的声音频率大小
const sum = data.reduce((a, b) => a + b) // 将这些值累加
return sum
}
html文件代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<script src="AudioAPI.js"></script>
<script type="text/javascript">
function fun(){
start().then(function(analyser){
setInterval(function() {
var voiceSize = getVoiceSize(analyser)
//doSomething after you got voice size
console.log(voiceSize);
}, 10)
})
}
fun();
</script>
</body>
</html>
打开html文件后报错提示是:
AudioAPI.js:27 Uncaught SyntaxError: Unexpected token }
以及:
index.html:11 Uncaught ReferenceError: start is not defined
at fun (index.html:11)
at index.html:20
请问怎么解决html中调用外部引用js方法的问题?