JS cannot get the src and other attributes of the audio being played / the duration of audio is NaN

intends to design a player, in which a function controls that a song can be played by clicking on the menu. Calling music.play () in this function and continuing to console.log (music.src) can display the src path normally.

however, in another function that controls the playback of the next song, both the output src and currentSrc are displayed undefined, and even related properties such as the output currentTime are displayed as 0. The related code is as follows:

function prevSong(msc){    //
        let s = msc.currentSrc;
        let tar;
        /*
           tar,
        */
        msc.pause();
        if(tar.previousSibling.nodeName == "LI"){
            let index = tar.previousSibling.innerHTML;
            msc.src = "src/music/"+index+".mp3";
        }else{
            let chd = tar.parentNode.childNodes;
            let res = chd[chd.length-1];
            msc.src = "src/music/"+res.innerHTML+".mp3"
        }
        //msc.load();
        msc.play();
    }

in addition, how to get the audio length duration? normally According to all kinds of online solutions, I use onloadedmetadata or even promise, to output NaN

.

send demo directly to post: http://www.malakh.xyz/demo2/
js: http://www.malakh.xyz/demo2/s.

Jul.01,2021

Audio needs to be loaded before it has corresponding attributes, otherwise it is all NaN.
because you need to replace src, dynamically and do not provide code, it is difficult to analyze the reason.
generally, you need to pause the object that is playing now, and then change the src property of the entity of the audio object before playing it.
you can refer to related codes such as jsplayer and jwplayer, which are well encapsulated.


can you give a demo describing the problem
https://jsfiddle.net/
http://jsbin.com/?html,js,? Output


you need to get audio in this way:

var player = $("-sharpmsc")[0];

if you get $("- sharpmsc") directly, you can play it directly by using the play property, but you cannot set the src property to the audio and get the audio frequently.
often get audio:

var duration = player.duration

if you get the playback address dynamically, you may not be able to get the playback address immediately when the audio is loaded for the first time, so you need to set a timer to detect duration every 10 milliseconds

//
    function getTime() {
        setTimeout(function () {
            var duration = player.duration;
            if (isNaN(duration)) {
                getTime();
            }
        }, 10);
    }
Menu