HTML5 / Javascript一次只播放一个音频样本

时间:2018-02-25 15:42:38

标签: javascript html5 html5-audio audio-streaming

我有以下代码,允许我按下按钮,播放和音频样本。它在这方面工作,但是,当我按下一个不同的按钮时,音符重叠,但我想按下一个按钮来停止播放前一个音符,并只播放与最近按钮推送相关的声音。我怎样才能做到这一点?

#!/usr/bin/env python3

import paho.mqtt.client as mqtt

client.subscribe("test/#")

def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))

client = mqtt.Client()
client.on_message = on_message
client.connect("localhost", 1883, 60)

client.loop_forever()

2 个答案:

答案 0 :(得分:-1)

HTML

<audio id="audio1">
    <source src="alarm.mp3" type="audio/mpeg" />
</audio>

的Javascript

var myAudio1 = document.getElementById("audio1");
myAudio1.play();

答案 1 :(得分:-1)

这就是我最终做的工作。我不知道是否有更有效的方法。

<!DOCTYPE html>


<script>

var e = new Audio('/Downloads/e-note.mp3');

var b = new Audio('/Downloads/b-note.mp3');
var g = new Audio('/Downloads/g-note.mp3');
var d = new Audio('/Downloads/d-note.mp3');
var a = new Audio('/Downloads/a-note.mp3');
var el = new Audio('/Downloads/elow-note.mp3');

    function play (note){

if (note==e) { 
b.pause(); g.pause(); d.pause(); a.pause(); el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.currentTime = 0;
note.play();
} 


if (note==b) {
e.pause();g.pause();d.pause();a.pause();el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

if (note==g) {
e.pause(); d.pause();b.pause();a.pause();el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

if (note==d) {
e.pause(); g.pause();b.pause();a.pause();el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

if (note==a) {
e.pause(); d.pause();b.pause();g.pause();el.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

if (note==el) {
e.pause(); d.pause();b.pause();g.pause();a.pause();
note.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);
note.pause();
note.pause();
note.currentTime = 0;
note.play();
} 

}


</script>

<button onclick="play(e)"> E </button>
<button onclick="play(b)"> B </button>
<button onclick="play(g)"> G </button>
<button onclick="play(d)"> D </button>
<button onclick="play(a)"> A </button>
<button onclick="play(el)"> E </button>


</html>