Search code examples
jquerysafariaudio-player

Safari won't play audio from javascript


I'm having a problem that Safari on the Mac won't play audio on a button click. I know auto-play is disabled, but this is based on user action so I'm really confused. Plays fine in other browsers.

In my webpage I use jquery to dynamically build up the page and I'm adding a button which will play audio like so:

var button = $('<button>', {
    id:      id + '_button',
    hidden:  'hidden',
    onclick: "preview('" + id + "')"
}).append($('<img>', {
    src: 'pb.gif',
    alt: 'Preview'
}));

And then in the preview method I play the sound.

function preview(rowId) {
    var url = 'ajax/preview.php?t=' + ... + '.mp3';  // Long URL build up here

    var snd = new Audio();
    snd.src = url;
    snd.play();
}

The strange thing is that for me the sound plays just fine in Safari when I click the button, but basically everyone else I've had try this says there's no sound.


Solution

  • The problem ended up being that the server was sending back the header as Content-Type: $contentType instead of expanding that variable. Once I fixed that it started working.