![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
icecast-metadata-player
Advanced tools
Simple to use Javascript class that plays an Icecast stream with real-time metadata updates
Icecast Metadata Player is browser library that plays streaming audio with full cross-platform codec support and real-time metadata updates.
<script>
tag.
See the main page of this repo for other Icecast JS tools: https://github.com/eshaz/icecast-metadata-js
audio/mpeg
, audio/mp4
audio/aac
, audio/mp4
audio/flac, application/ogg
, audio/mp4
application/ogg
, audio/mp4
, audio/webm
application/ogg
, audio/webm
npm i icecast-metadata-player
Example
import IcecastMetadataPlayer from "icecast-metadata-player";
const player = new IcecastMetadataPlayer(
"https://dsmrad.io/stream/isics-all",
{ onMetadata: (metadata) => {console.log(metadata)} }
);
Download all of the files here for the latest build and save these to a path on your server.
*.js
files must be saved into the same path on your server.*.js.map
files are optional source maps for debugging.
Filename | Functionality |
---|---|
icecast-metadata-player-1.17.9.main.min.js | Core functionality (playback, metadata) Use this file in your <script> tag |
icecast-metadata-player-1.17.9.synaudio.min.js | Gapless playback support |
icecast-metadata-player-1.17.9.mediasource.min.js | Mediasource playback support |
icecast-metadata-player-1.17.9.mpeg.min.js | MPEG playback support (webaudio) |
icecast-metadata-player-1.17.9.flac.min.js | FLAC playback support (webaudio) |
icecast-metadata-player-1.17.9.opus.min.js | Opus playback support (webaudio) |
icecast-metadata-player-1.17.9.vorbis.min.js | Vorbis playback support (webaudio) |
icecast-metadata-player-1.17.9.common.min.js | Common functions (webaudio) |
Add a <script>
tag referencing icecast-metadata-player-1.17.9.main.min.js
in your html.
IcecastMetadataPlayer
is made available as a global variable in your webpage to use wherever.
Example
<script src="icecast-metadata-player-1.17.9.main.min.js"></script>
<script>
const onMetadata = (metadata) => {
document.getElementById("metadata").innerHTML = metadata.StreamTitle;
};
const player =
new IcecastMetadataPlayer(
"https://dsmrad.io/stream/isics-all",
{ onMetadata }
);
</script>
<body>
<button onclick="player.play();"> Play </button>
<button onclick="player.stop();"> Stop </button>
<p> Now Playing: <span id="metadata"></span> </p>
</body>
To use IcecastMetadataPlayer
, create a new instance by passing in the stream endpoint, and the options object (optional). See the Options and Callbacks sections for more information.
const player = new IcecastMetadataPlayer("https://stream.example.com", {
onMetadata: (metadata) => {console.log(metadata)},
...options
})
IcecastMetadataPlayer supports reading ICY metadata, Ogg (Vorbis Comment) metadata, or both. Each section below describes how to instantiate IcecastMetadataPlayer
to use these different metadata types.
When reading ICY metadata, the client should be able to read the Icy-MetaInt
header value on the response. If the CORS policy does not allow clients to read the Icy-MetaInt
header, then IcecastMetadataPlayer
will attempt to detect the metadata interval based on the incoming request data.
const player = new IcecastMetadataPlayer("https://stream.example.com/stream.mp3", {
onMetadata: (metadata) => {console.log(metadata)},
metadataTypes: ["icy"]
...options
})
Ogg (Vorbis Comment) metadata, if available, usually offers more detail than ICY metadata.
const player = new IcecastMetadataPlayer("https://stream.example.com/stream.opus", {
onMetadata: (metadata) => {console.log(metadata)},
metadataTypes: ["ogg"]
...options
})
ICY and Ogg metadata can both be read from the stream. Usually a stream will only have one or the other, but this option is possible if needed.
const player = new IcecastMetadataPlayer("https://stream.example.com/stream.flac", {
onMetadata: (metadata) => {console.log(metadata)},
metadataTypes: ["icy", "ogg"]
...options
})
To begin playing a stream, call the .play()
method on the instance.
Note: IcecastMetadataPlayer will use either the MediaSource api or, if that is not available, HTML5 audio with a second request for metadata.
const player = new IcecastMetadataPlayer("https://stream.example.com/stream.flac", {
onMetadata: (metadata) => {console.log(metadata)},
metadataTypes: ["icy"]
...options
})
player.play();
Metadata will be sent as soon as it is discovered via the onMetadataEnqueue
callback and when the metadata is synchronized with the audio via the onMetadata
callback. See the Methods section below for additional callbacks.
{
StreamTitle: "The stream's title", // ICY
StreamUrl: "The stream's url", // ICY
TITLE: "The stream's title", // Ogg
ARTIST: "The stream's artist", // Ogg
ALBUM: "The stream's album" // Ogg
}
To stop playing the stream, call the stop()
method on the instance.
player.stop();
See the HTML demos for examples.
IcecastMetadataPlayer enables retry / reconnect logic by default. When a fetch or network error occurs, IcecastMetadataPlayer will attempt to recover by retrying the fetch request.
This allows for seamless audio playback when switching networks, (i.e. from a cell network to a Wifi network).
See Retry Options to configure or disable reconnects.
error
/ onError
event will be fired indicating the issue that caused the retry process to start.options
object.
retry
/ onRetry
event.stop()
is called.streamstart
/ onStreamStart
event will be fired and the audio will restart playing from the new request.
retrytimeout
/ onRetryTimeout
event will be fired and the stream will stop.The audio will continue to play until the buffer runs out while reconnecting. If the reconnect is successful before the buffer runs out, there will be no gap in playback.
To increase the amount of audio that is buffered by clients, increase the <burst-size>
setting in your Icecast server.
IcecastMetadataPlayer enables the stream endpoint to be switched during playback to any new endpoint by calling switchEndpoint
.
The next endpoint will fetched and attempted to be synchronized with playback from the previous endpoint. The next endpoint is selected from either from the current list of endpoints, or the new passed in list. The transition from the old to new stream should be seamless using synchronization logic that first attempts to match the frame data exactly using CRC32 hashes, and if there is no exact match, by synchronizing the PCM streams using cross-correlation.
switchEndpoint
lifecycleenableLogging
is set to true
.
player.play()
async
player.stop()
async
player.switchEndpoint(endpoints, options)
async
endpoints
optional Single URL or Array of URLs for the new stream endpoint(s). When left empty, and when multiple stream endpoints are present on the instance, the next URL will be selected.options
optional Object containing any new options to apply to the instance. All options are allowed except callbacks and the audio element. See options for more details.player.detachAudioElement()
IcecastMetadataPlayer.canPlayType(mimeType)
static
{mediasource, html5, webaudio}
containing a string value indicating if passed in mime-type can be played.""
- Cannot play the codec"maybe"
- Might be able to play the codec"probably"
- Should be able to play the codecplayer.audioElement
player.endpoint
player.icyMetaInt
player.metadataQueue
metadata
in FIFO order.
[
{
metadata: { StreamTitle: "Title 1" },
timestampOffset: 2.5,
timestamp: 1
},
{
metadata: { StreamTitle: "Title 2" },
timestampOffset: 5,
timestamp: 2
}
]
player.state
"loading", "playing", "stopping", "stopped", "retrying"
player.playbackMethod
"mediasource", "webaudio", "html5"
You can create any number of instances of IcecastMetadataPlayer on your webpage.
Each instance must have it's own audio element.
const player_1 = new IcecastMetadataPlayer("https://example.com/stream_1", {
...options,
...callbacks
});
const player_2 = new IcecastMetadataPlayer("https://example.com/stream_2", {
...options,
...callbacks
})
endpoints
(required)
endpointOrder
(optional) - default ordered
ordered
to select each endpoint in the order they were provided.random
to select each endpoint in random order.audioElement
(optional) - Default new Audio()
bufferLength
(optional) - Default 1
enableLogging
(optional) Default false
true
to enable warning and error logging to the consoleenableCodecUpdate
(optional) Default false
true
to enable the codecupdate
event.onCodecUpdate
callback is present.playbackMethod
(optional) Default mediasource
"mediasource", "webaudio", "html5"
authentication
(optional) Default disabled
Authorization
header in the HTTP request using basic auth.{user: 'myuser', password: 'mypassword'}
retryTimeout
(optional) - Default 30
seconds
0
to disable retries(advanced retry logic)
retryDelayMin
(optional) - Default 0.5
seconds
retryDelayMax
(optional) - Default 2
seconds
retryDelayRate
(optional) - Default 0.1
i.e. 10%
metadataTypes
(optional) - Default ["icy"]
[]
- Will not parse metadata["icy"]
- Default Parse ICY metadata only["ogg"]
- Parse Ogg (vorbis comment) metadata only["icy", "ogg"]
- Parse both ICY and Ogg metadata["icy"]
metadata type is enabledicyMetaInt
(optional) Default reads from the response header
Icy-MetaInt
header in the responseicyCharacterEncoding
(optional) Default "uft-8"
utf-8
, but encodings such as iso-8859-2
are also used.icyDetectionTimeout
(optional) Default 2000
0
to disable metadata detectiononMetadata(metadata, timestampOffset, timestamp)
Called when metadata is synchronized with the audio.
metadata
ICY or Ogg metadata in an object of key value pairs
{ "StreamTitle: "The Stream Title" }
{ "TITLE: "The Stream Title", "ARTIST": "Artist 1; Artist 2"... }
timestampOffset
time in seconds when is scheduled to be updated.timestamp
time in seconds when metadata was discovered on the stream.onMetadataEnqueue(metadata, timestampOffset, timestamp)
Called when metadata is discovered on the stream.
metadata
ICY or Ogg metadata in an object of key value pairs
{ "StreamTitle: "The Stream Title" }
{ "TITLE: "The Stream Title", "ARTIST": "Artist 1; Artist 2"... }
timestampOffset
time in seconds when is scheduled to be updated.timestamp
time in seconds when metadata was discovered on the stream.onLoad()
Called when the fetch request is started.onStreamStart()
Called when fetch request begins to return data.onBuffer(time)
Called when the audio buffer is being filled.onPlay()
Called when the audio element begins playing.onStream(streamData)
Called when stream data is sent to the audio element.onStreamEnd()
Called when the fetch request completes.onStop()
Called when the stream is completely stopped and all cleanup operations are complete.onRetry()
Called when a retry / reconnect is attempted.onRetryTimeout()
Called when the retry / reconnect attempts have stopped because they have timed-out.onWarn(message, ...messages)
Called with message(s) when a warning condition is met.onError(message, error)
Called with a message and an Error object when an exception occurs when a fallback or error condition is met.onCodecUpdate(codecInformation, updateTimestamp)
Called with audio codec information whenever there is a change. This callback is synchronized with the audio.
codecInformation
such as bitrate
and samplingRate
are passed in as an objectupdateTimestamp
is the time in seconds within the audio stream when the codec information was updatedEach callback is made available as an event. The parameters for each callback are passed into event.details
as an array.
player.addEventListener('metadata', (event) => {
const [metadata, timestampOffset, timestamp] = event.detail;
})
IcecastMetadataPlayer builds are supplied with a source map, which allows the minified code to be viewed as fully formatted code in a browser debugger.
icecast-metadata-player-1.17.9.min.js.map
located in the build folder of this project to the location along side icecast-metadata-player-1.17.9.min.js
in your website.ICY Metadata has incorrect characters such as "Zanzibar - Sz�lj M�r" when it should be "Zanzibar - Szólj Már"
icyCharacterEncoding
option to match the character encoding of the metadata.utf-8
is iso-8859-2
I have an authenticated stream, and when I supply credentials in the
authentication
option, I get a CORS error.
Authorization
listed in the Access-Control-Allow-Headers
header when it responses to the CORS OPTIONS
request.Access-Control-Allow-Headers: Origin, Icy-MetaData, Range, Authorization
Note: Warning messages are be enabled by setting options.enableLogging = true
Reconnected successfully after retry event. Found 145 frames (3.788 seconds) of overlapping audio data in new request. Synchronized old and new request.
Reconnected successfully after retry event. Found no overlapping frames from previous request. Unable to sync old and new request.
burst-size
option (or equivalent) in your Icecast configuration to increase the client's buffered data.Passed in Icy-MetaInt is invalid. Attempting to detect ICY Metadata.
Icy-MetaInt
header. IcecastMetadataPlayer
will attempt to detect the ICY metadata interval, and will timeout after a default of 2 seconds, or the value in milliseconds passed into the icyDetectionTimeout
option.This stream is not an Ogg stream. No Ogg metadata will be returned.
"ogg"
passed into the metadataTypes
options, but the stream response is not an ogg stream. ICY metadata and the stream will work without issues. Please remove the "ogg"
option to remove this warning.This stream was requested with ICY metadata. If there is a CORS preflight failure, try removing "icy" from the metadataTypes option.
Icy-MetaData: 1
header.
Icy-Metadata
header. If you want ICY metadata, your CORS policy must allow this header to be requested. See CORS Troubleshooting for more information.Your browser does not support this audio codec mime-type
Unsupported Codec mime-type
The audio element encountered an error
NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
NotAllowedError: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD
FAQs
Simple to use Javascript class that plays an Icecast stream with real-time metadata updates
The npm package icecast-metadata-player receives a total of 0 weekly downloads. As such, icecast-metadata-player popularity was classified as not popular.
We found that icecast-metadata-player demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.