HTML 5 - “内联”播放小型 mp3

发布于 2024-12-24 17:34:43 字数 459 浏览 3 评论 0 原文

我想使用 HTML 5 音频支持来播放 mp3。 我试图使用音频标签,但现在我使用 javascript 来实现。

我的“播放器”只是一个很小的播放图像,按下时会播放音频(并非所有带有进度的音频控制)。

我正在尝试使用 javascript 来播放它。

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

这是我的代码,它不起作用。当我单击作为我的“播放”按钮的图像时,它执行正常。

Url 是一个包含文件 url 的字符串。

我正在最新版本的 Chrome 和 FF 中进行测试。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温折酒 2024-12-31 17:34:43

尝试监听 canplay 尝试播放 mp3 之前的事件。以下是如何执行此操作的示例:

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

当浏览器可以开始播放 mp3 时,会触发 canplay 事件,但它不保证可以完整播放 mp3。如果这不适合您的目的,您可以收听其他一些相关事件,例如 loadeddatacanplaythrough

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文