本地图片/音频无法在网站显示,音频路径疑存问题求助
本地音频/图片无法在网站加载的问题解决
问题根源
你代码里用的是本地绝对路径(C://Users//ADMIN//Desktop//Web development_new//HTML_CSS//Project_spotify//data//PhotoGraph.mp3),浏览器出于安全机制,禁止网页直接读取用户本地文件系统的资源——哪怕路径完全正确也不行,这是为了防止恶意网页窃取本地文件。
解决步骤
把资源移到项目目录内,用相对路径引用
把音频文件放到你的网站项目文件夹里,比如在Project_spotify下新建assets/audio目录,将PhotoGraph.mp3放进去。然后用相对路径替换绝对路径:
修改后的代码片段:// Initialize variables let songIndex = 0; // 用项目内的相对路径 let audioElement = new Audio('./assets/audio/PhotoGraph.mp3'); let masterplay = document.getElementById('masterplay'); let bar = document.getElementById('myBar') // Play / Pause masterplay.addEventListener('click', () => { if (audioElement.paused || audioElement.currentTime <= 0) { audioElement.play(); masterplay.classList.remove('fa-circle-play'); masterplay.classList.add('fa-pause-circle'); } else { audioElement.pause(); masterplay.classList.remove('fa-pause-circle'); masterplay.classList.add('fa-circle-play'); } }) // Listen to events bar.addEventListener('timeupdate', () => { console.log('timeupdate') // Updates Seekbar })相对路径的规则:
./表示当前HTML文件所在目录,比如你的HTML在Project_spotify根目录,./assets/audio/PhotoGraph.mp3就指向根目录下的assets/audio文件夹里的音频。用本地服务器运行项目
直接双击打开HTML文件(以file://协议加载)时,部分浏览器仍会限制资源访问。推荐用本地服务器运行:- VS Code用户可以安装
Live Server插件,右键HTML文件选择「Open with Live Server」,页面会以http://localhost:xxxx形式加载。 - 用Python的话,在项目根目录打开终端,运行
python -m http.server 8000(Python3),然后访问http://localhost:8000。
- VS Code用户可以安装
检查路径细节
确认文件名、文件夹名的大小写完全正确(比如photograph.mp3和PhotoGraph.mp3是两个不同的文件,Linux/macOS系统会区分),后缀.mp3也不能漏写。
内容的提问来源于stack exchange,提问作者Preet Mutha
相关产品推荐
相关产品推荐

