HTML 5 - Play tiny mp3 “inline”

允我心安 提交于 2019-12-01 18:50:28

问题


I want to play a mp3 using HTML 5 audio support. I was trying to use an audio tag but now I am doing it using javascript.

My "Player" will be just a tiny Play image, that when is pressed plays the audio (not all the audio control with progress).

I am trying to play it using javascript .

function playmp3(url){
   var audioElement = document.createElement('audio');
   audioElement.setAttribute('src', url);
   audioElement.load();
   audioElement.play();
}

This is my code and it does not work. It executes ok when I click an image that is my Play button.

Url is a string that contains the url of a file.

I am testing in the newest versions of Chrome and FF.


回答1:


Trying listening for the canplay event before attempting to play the mp3. Here's an example of how to do that:

function playmp3(url){
    var audioElement = document.createElement('audio');
    audioElement.setAttribute('src', url);
    audioElement.load();
    audioElement.addEventListener("canplay", function() {
        audioElement.play();
    });
}

The canplay event is fired when the browser can start playing the mp3, but it doesn't guarantee that it can play the mp3 to completion. If that doesn't suite your purposes, there are a couple of other related events that you can listen to such as loadeddata and canplaythrough.



来源:https://stackoverflow.com/questions/8703975/html-5-play-tiny-mp3-inline

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