我这里有一个组件,应该允许用户播放当前歌曲并从他们的计算机添加新歌曲。这是代码
import React, {useState} from 'react';
const SongListUI = () => {
const [songs, setSongs] = useState([])
const [oneSong, setSong] = useState('')
const [Artist, setArtist] = useState('')
const [src, setSrc] = useState('')
const addSong = (oneSong, Artist) =>{
setSongs([...songs, {title: oneSong, artist: Artist, source: src, id: Math.random(0,1)}])
}
const handleSubmit = (e) =>{
e.preventDefault()
addSong(oneSong, Artist, src)
}
return (
<div className="hi">
{
songs.map(song =>{
return(
<div key={song.id}>
<h4>{song.title}</h4>
<audio controls>
<source src={song.source} type="audio/mpeg" />
</audio>
<h3>{song.artist}</h3>
</div>
)
})
}
<form onSubmit={handleSubmit}>
<label>addSong</label>
<input type="text" value={oneSong} onChange={(e) => setSong(e.target.value)}/>
<input type="text" value={Artist} onChange={(e) => setArtist(e.target.value)}/>
<input type="file" value={src} onChange={(e) => setSrc(e.target.value)}/>
<input type="submit" value="Add a Song"/>
</form>
</div>
);
}
export default SongListUI;
问题是每当我尝试通过文件输入从计算机上传mp3文件时,我都会收到错误:不允许加载本地资源:file:///C:/fakepath/Black%20Sabbath%20-%20Paranoid%20(Full%20Album(.mp3 我该如何解决这个问题?
您是否使用 Chrome 作为浏览器?如果是,那么可能 chrome 出于某些安全问题阻止您的本地文件访问。这是这部分: "file:///C:/fakepath/Black%20Sabbath%20-%20偏执狂%20(完整%20专辑(.mp3">
尝试在某些云服务器中上传您的文件,例如:http://yourserver/your/path.mp3
或者尝试将其放在 react 根文件夹中的某个位置,然后像这样访问它:
const source = ./yourfilename.mp3
<source src={source} type="audio/mpeg" />