/    Sign up×
Community /Pin to ProfileBookmark

play random background bgm in javascript

i have the following code in the function init, and init is called, but when i load the webpage, no music is played. What am i missing? The mp3 files are in the same folder as the code.

“`
var numberOfSongs = 6
var sound = new Array(numberOfSongs+1)
sound[0]= “wen.mp3”
sound[1]= “wen.mp3”
sound[2]= “wen.mp3”
sound[3]= “wen.mp3”
sound[4]= “wen.mp3”
sound[5]= “wen.mp3”

function randomNumber(){
var randomLooper = -1
while (randomLooper < 0 || randomLooper > numberOfSongs || isNaN(randomLooper)){ randomLooper = parseInt(Math.random()*(numberOfSongs+1))
}
return randomLooper
}
var randomsub = randomNumber()
var soundFile = sound[randomsub]
document.write (‘<EMBED src= “‘ + soundFile + ‘” hidden=true type=”audio/mpeg” autostart=true loop=true>’)
“`

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumDec 29.2019 — This code is outdated:
  • - For playing audio there exists the audio object now

  • - Random index can be calculated precisely, no need for trial&error code

  • - document.write can be subject of unexpected behaviour and should not be used

    Keeping this in mind your code might be changed to this:
    function randomSong() {
    var audioObj = new Audio();
    var songs = [
    "song1.mp3",
    "song2.mp3",
    "song3.mp3",
    "song4.mp3"
    ];
    var idx = Math.floor(Math.random() * songs.length);
    audioObj.src = songs[idx];
    audioObj.play();
    }

    Having done this I ran into another issue: My browser (Opera) doesn't play the song automatically but writes to the console: "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD"

    The reason is that background music being played automatically is not welcome by many users. I recommend to use a play button instead.
  • ×

    Success!

    Help @zhanzhao spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.25,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...