使用 JavaScript 引用 URL 来播放声音?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10142867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reference URL with JavaScript to play sound?
提问by JColling
Im using soundcloud dot com to upload my sounds. i want to press a button within my mobile application and have that sound play.
我使用 soundcloud dot com 上传我的声音。我想在我的移动应用程序中按下一个按钮并播放那个声音。
So basically i want my sound to be referenced from the URL that I am given when the button is pressed by the user.
所以基本上我希望我的声音从用户按下按钮时给出的 URL 中引用。
I need to do it with Javascript only. No HTML 5 please. Any help is greatly appreciated cause this is Xtremely frustrating. Any ideas? Thanks in advance.
我只需要用 Javascript 来做。请不要使用 HTML 5。非常感谢任何帮助,因为这非常令人沮丧。有任何想法吗?提前致谢。
回答by nickf
It's pretty simple to get started really:
真正开始非常简单:
function playSound(url) {
var a = new Audio(url);
a.play();
}
Use that as whatever event handler you want for your application. Of course, I'd hope you'd want to do more than just play (for example, maybe pause would be good too?), but it's a start.
将其用作您的应用程序所需的任何事件处理程序。当然,我希望你想做的不仅仅是玩(例如,也许暂停也不错?),但这是一个开始。
回答by Larry Battle
Use jPlayer to play sound using Javascript. This will take you a lot of time and frustration.
使用 jPlayer 使用 Javascript 播放声音。这将花费你很多时间和挫折。
jplayer.org/
jplayer.org/
Here's what your code might look like with jPlayer. Note: You're not forced to use a skin with jPlayer because all it is is just an API to play audio.
以下是您的代码在 jPlayer 中的样子。注意:您不会被迫在 jPlayer 中使用皮肤,因为它只是一个播放音频的 API。
Example code to play a video or audio on load.
在加载时播放视频或音频的示例代码。
$(function() { // executed when $(document).ready()
$("#jpId").jPlayer( {
ready: function () {
$(this).jPlayer("setMedia", {
m4v: "http://www.myDomain.com/myVideo.m4v" // Defines the m4v url
}).jPlayer("play"); // Attempts to Auto-Play the media
},
supplied: "m4v",
swfPath: "jPlayer/js"
});
});