I'm trying to know when sound is actually coming out from the user speakers, if that makes any sense.
I have the following:
const stream = new Audio("https://stream1.srvnetplus.com:18122/stream");
const loading = false;
async function play() {
loading = true;
// stream.play() returns a Promise<void>
await stream.play();
loading = false;
}
loading is set to false, but for some reason actual sound comes out of my speakers after 1 — 2 seconds in some ocassions.
This react library (react-audio-player) has an event called onCanPlay. As per the docs state:
| Event | Type | Description |
|---|---|---|
| onCanPlay | Function | called when enough of the file has been downloaded to be able to start playing. Passed the event. |
This makes me think that the await in await stream.play(); is not enough to know when actual audio is being played. Correct me if i'm wrong.
I would like a solution that looks something like this:
const stream = new Audio("https://stream1.srvnetplus.com:18122/stream");
const loading = false;
async function play() {
loading = true;
const res = await stream.play();
await res.ready();
loading = false;
}
CodePudding user response:
Solved my problem with howler.js
import { Howl } from "howler";
const streamUrl = "https://stream1.srvnetplus.com:18122/stream";
const stream = new Howl({
src: [streamUrl],
html5: true,
preload: true,
});
const loading = false;
function play() {
loading = true;
stream.play();
stream.on("play", () => {
loading = false;
});
}
CodePudding user response:
All of the <audio> events could be logged and shown in the example below. The playing event fires after the audio playback begins.
function initPlayback() {
const audio = document.querySelector('audio')
event.target.remove() // remove <button>
audio.hidden = false;
// log all events of <audio>, except timeupdate (too verbose)
['audioprocess', 'canplay', 'canplaythrough', 'complete', 'durationchange',
'emptied', 'ended', 'loadeddata', 'loadedmetadata', 'pause', 'play',
'playing', 'ratechange', 'seeked', 'seeking', 'stalled', 'suspend',
// 'timeupdate'
'volumechange', 'waiting']
.forEach(name => audio.addEventListener(name, event => {
console.log(name)
}))
audio.src = 'https://stream1.srvnetplus.com:18122/stream'
audio.play()
.then(() => console.log('play() resolved'))
}
<audio controls hidden></audio>
<button onclick="initPlayback()" style="padding: 1em 2em;">Play</button>
