简体   繁体   中英

audio.play() function returns a TypeError: not a function

As an excersize I am making a React App using the spotify API. I am trying to add a preview feature so that the user can play a 30 second mp3 on the click of a button. I have the url to the mp3, but when I try to play it, the console logs the following error: Uncaught TypeError: previewUrl.play is not a function at PlayButton.playMusic (PlayButton.js:18:1)

first I thought that the function might not recognize the url as an.mp3 so I tried adding that extension to the url. If I open the url directly, it works, but not on my button click using a.play() function.

The code of my component is the following

export class PlayButton extends React.Component {
    constructor(props) {
        super(props);
        this.playMusic = this.playMusic.bind(this)
    }

    playMusic() {
        const previewUrl = this.props.audioFile + '.mp3';
        previewUrl.play();
    }

    render() {
        return (
            <div>
                <button className="playButton" onClick={this.playMusic} ><FontAwesomeIcon icon={faPlay} /></button>
            </div>
        )
    }
}

I will give you an example URL, https://p.scdn.co/mp3-preview/5f9499330054385118929b2af715ea5b0fcde96b?cid=b5e1d8396281443d8a60632314dbe0b9.mp3

I keep trying for this one to play, but so far to no avail.

Any help is welcome, thanks

You are trying to invoke the HTML method .play() on what seems to be a string since you are doing

this.props.audioFile + '.mp3'

Make sure you are executing this method on a valid HTMLMedia element. Could u share what are u sending as audioFile in props?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM