Html5 audio won't play in safari when the source is populated via JavaScript

浪子不回头ぞ 提交于 2020-04-15 22:39:36

问题


I am building a playlist in my Rails app and I am having some issues getting audio to play in Safari. If the html5 audio element's source is hard-coded, it plays just fine in safari but when it is populated via javascript, it does not play. this works just fine in Chrome and IE, but not in Safari.

Here is the Ruby for the playlist entry:

.playlist_column
  -@music_posts.each do |post|
    .entry{:id => post.id, :data => {:post_id => post.id, :source => post.mp3.url}}

and here is the audio element, preloaded with the first track's source:

.playlist_player
  %audio{:controls => "controls", :id => @music_posts.first.id}
    %source{:src => @music_posts.first.mp3.url, :type => "audio/mp3"}

Here is the JavaScript:

$(".entry").click(function(){
  var current_entry = $(this);
  var this_track = current_entry.data("source");
  var audio = $("audio").get(0);
  var audio_source = $("audio source");

  audio_source.attr("src", this_track);
  audio.load();
  audio.play();

});

When I inspect the audio element in safari, it looks exactly like it should, with the proper source:

<audio controls="controls" id="7">
  <source src="http://s3.amazonaws.com/blog/posts/5/song/07%20-%20Young%20Blood.mp3?1328052011" type="audio/mp3">
</audio>

But it won't play and I am not seeing any errors, any ideas? Thanks in advance.


回答1:


Check out the HTML spec for the src attribute on an existing source element:

Note: Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.

Since you (theoretically) know that the audio file type is playable, you can just do

var audio = $("audio").get(0);
audio.src = this_track;
audio.load();
audio.play();

I just tested that in Safari and it appears to work correctly.




回答2:


type => "audio/mpeg"

That should fix it. A suggestion - please give id for audio elements and use it in jQuery instead of tag name.



来源:https://stackoverflow.com/questions/9271006/html5-audio-wont-play-in-safari-when-the-source-is-populated-via-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!