尝试使用JavaScript播放音频

尝试使用JavaScript播放音频

本文介绍了尝试使用JavaScript播放音频。但是不是在玩?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在努力制作一个广播电台项目。在一开始它将播放一个音频文件,如:欢迎来到97.5的节拍或其他什么,然后它会选择一个随机的歌曲,并在它结束后,它将播放一个音频文件说这是一个很棒的节拍。到下一个!它会发出不同的随机歌曲

So I am trying to make a radio station project just for fun. Where in the start it will play an audio file saying like: "Welcome to the beat at 97.5" or whatever and then it would choose a random song and after it ends it would play an audio file saying "that was the awesome beat. Moving on to the next!" and it would play a different random song

令人兴奋的部分!码!
我试过这样做:

Exciting part! Code!I tried doing this:

var audio = new Audio("test.mp3");
audio.play();

它不会发挥任何作用?什么是使用JavaScript播放音频的最简单,最快捷的方式?请不要涉及HTML。

It just wouldnt play anything? Whats the easiest and fastest way to play an audio with JavaScript? Please no HTML involved.

编辑:尝试使用Howler.js,但仍然无法做任何事情?这是代码:

Tried to use Howler.js but wouldnt do anything still? Here is the code:

//I moved it
var sound = new Howl({
  urls: ['/audio/test.mp3']
}).play();

这是目录:C:\ Websites\infiniteradiostation\audio\test.mp3

this is the directory: C:\Websites\infiniteradiostation\audio\test.mp3

推荐答案

您发布的代码看起来不错,请检查javascript控制台没有错误并确保路径该文件是正确的。

The code you have posted looks good, please check the javascript console that there are no errors and make sure that the path of the file is correct.

除此之外,您还可以使用多个选项来增强功能。

Other than that you also have multiple options that you can use to enhance the functionality.

是一个出色的库,提供大量功能(以及向后兼容性)如果你愿意也可以。)

SoundManager2 is an excellent library that provides tons of features(and backward compatibility too if you prefer).

示例代码将是这样的。

<script src="/path/to/soundmanager2.js"></script>
<script>
soundManager.setup({
  url: '/path/to/swf-files/',
  onready: function() {
    var mySound = soundManager.createSound({
      id: 'aSound',
      url: '/path/to/an.mp3'
    });
    mySound.play();
  }
});
</script>





太优秀的图书馆值得一看。它的示例代码会是这样的东西

Howler.js

Howler too an excellent library thats worth looking.Its example code will be some thing like this

var sound = new Howl({
  urls: ['sound.mp3', 'sound.ogg', 'sound.wav'],
  autoplay: true,
  loop: true,
  volume: 0.5,
  onend: function() {
    alert('Finished!');
  }
});

这篇关于尝试使用JavaScript播放音频。但是不是在玩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:57