:musical_score: ts-audio is an agnostic library that makes it easy to work with AudioContext and create audio playlists in the browser

Overview

ts-audio · Build Status license

ts-audio is an agnostic and easy-to-use library to work with the AudioContext API and create Playlists.

Features

  • Simple API that abstracts the complexity of the AudioContext API
  • Cross-browser support
  • Makes easy to create audio playlist
  • Works with any language that compiles to JavaScript
  • Supports to Types
  • Zero-dependecy

Installation

To install ts-audio, execute:

$ npm install ts-audio

or

$ yarn add ts-audio

Quickstart

ts-audio has two components at its core: Audio and AudioPlaylist. Both components are functions that you can call with certain parameters.

Below is an example of how to use the Audio:

import Audio from 'ts-audio';

const audio = Audio({
  file: './song.mp3',
  loop: true,
  volume: 0.2,
});

audio.play();

To use the AudioPlaylist component is also quite simple:

import { AudioPlaylist } from 'ts-audio';

const playlist = AudioPlaylist({
  files: ['./songOne.mp3', './songTwo.mp3', './songThree.mp3'],
  volume: 0.7,
});

playlist.play();

Docs

License

MIT

Comments
  • Added functionality for playing sound again

    Added functionality for playing sound again

    Fixed issue with web audio API that allowed only one play and stop. Actually the audioContext object is recreated and re-connected now. Some JSHint fixes also came through (sorry about that)

    opened by netgfx 9
  • window is not defined

    window is not defined

    I'm getting a window is not defined when calling: const audio = Audio({ file:myAudioFile, volume: 1, });

    Running in Next.JS environment. Has anyone seen this before?

    opened by bradwoods 5
  • Feature Request: Reuse sounds

    Feature Request: Reuse sounds

    Scenario: I want to create a game capable of playing the same sound multiple times and possibily at the same time.

    It would be good if I had a SoundBuffer fetching the data into memory and then a separate Audio class, which can be used to play that SoundBuffer without having to re-download for every new Audio instance.

    opened by Lusito 4
  • Note: audioJS is NOT compatible with current FF release

    Note: audioJS is NOT compatible with current FF release

    In contradiction with what is stated, AudioContext is NOT supported by FF 23, nor 24. It's only available in the nightlies ATM. It's set to ship with FF 25.

    https://developer.mozilla.org/en-US/docs/Web/API/AudioContext#Browser_compatibility

    opened by oh-ren 3
  • Feature request: implement getter/setter for current play time

    Feature request: implement getter/setter for current play time

    I really like the playlist feature of this library, but I would like to be able to get and update the current time position of the audio being played. This would allow React implementations to display the current play time and also allow users to scrub through audio files.

    This feature could be implemented directly or you could give developers the ability to implement this functionality by exposing the audio context (https://github.com/EvandroLG/ts-audio/issues/41)

    Helpful links:

    • https://developer.mozilla.org/en-US/docs/Web/API/AudioBufferSourceNode/start
    • https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/currentTime
    opened by MrLuit 2
  • Creating an audioJS player and delaying playback doesn't play

    Creating an audioJS player and delaying playback doesn't play

    It appears there's a missing logic path for creating an audioJS object and delaying the playback. shouldPlay gets set to true, but nothing happens after that.

    opened by MrBendel 2
  • A logo for the project

    A logo for the project

    Yo Evandro! I've made a logo for this project, check it out:

    | ts-audio | README.md | | --- | --- |

    Let me know what you think of it! Note that it supports both light and dark themes, as well as the reduced motion preference.

    opened by gibatronic 1
  • Unused dependencies

    Unused dependencies

    It seems none of your dependencies are used. They are installed without being needed when you install ts-audio. I noticed because playlist > glob > minimatch has a high vulnerability (npm audit).

    Could you remove all of the unused dependencies?

    opened by Lusito 1
  • fix safari audiocontext issue

    fix safari audiocontext issue

    Per the AudioContext() docs, Safari requires a vendor prefix.

    AudioContext() does not work on Safari (checked with v13.1), so a fallback was added to webkitAudioContext().

    opened by kevinselwyn 1
  • I use this code on firefox

    I use this code on firefox

    I use this code on firefox.

    https://github.com/junhuanchen/webduino-module-azrue-speech/blob/79629695d6a87efba81287f566c0ce375ec09aff/audioJS.js#L150

    https://github.com/junhuanchen/webduino-module-azrue-speech/blob/79629695d6a87efba81287f566c0ce375ec09aff/audioJS.js#L114

    https://github.com/junhuanchen/webduino-module-azrue-speech/blob/79629695d6a87efba81287f566c0ce375ec09aff/audioJS.js#L99-L100

    maybe need fix this.source.gain func.

    opened by junhuanchen 1
  • Added support for loop and volume functionalities

    Added support for loop and volume functionalities

    User can now select to loop the selected audio, and/or change the volume.

    These functionalities are quite important especially for use in HTML5 Gaming audio procedures.

    User can now set loop and volume parameters or they default to false and 1 (highest volume)

    opened by netgfx 1
  • AudioPlaylist cannot automatically play next song

    AudioPlaylist cannot automatically play next song

    Hi there! Love this library, you have done a fantastic job. I am making a simple audio player, and wrote up the following code below - however, the playlist does not automatically move onto the next song in the list after the current one finishes. I've tried setting loop to true, enabling shuffle, and playlist.end doesn't seem to work.

    Here is the code below, is there something I'm missing? Using 0.7.0, latest release.

    import { useState, useMemo, useEffect, useRef } from "react";
    import {
      IoMdPlay,
      IoMdPause,
      IoMdSkipForward,
      IoMdSkipBackward,
      IoMdMusicalNote,
      IoMdMusicalNotes,
    } from "react-icons/io";
    import { AudioPlaylist } from "ts-audio";
    import FatsNY from "../assets/mp3/FatsNY.mp3";
    import PictureBall from "../assets/mp3/PictureBall.mp3";
    import Silvery from "../assets/mp3/Silvery.mp3";
    import SecretGarden from "../assets/mp3/SecretGarden.mp3";
    
    export default function MusicPlayer(props: any) {
      const [currentSong, setCurrentSong] = useState(0);
      const [isPlaying, setIsPlaying] = useState(false);
    
      interface Song {
        title: string;
        artist: string;
        img_src: any;
        src: string;
      }
    
      const songs: Song[] = useMemo(
        () => [
          {
            title: "At the Moving Picture Ball",
            artist: "Maurice Burkhart",
            img_src: IoMdMusicalNote,
            src: PictureBall,
          },
          {
            title: "New York Yacht Club",
            artist: "Fats Waller",
            img_src: IoMdMusicalNote,
            src: FatsNY,
          },
          {
            title: "By the Lights of the Silvery",
            artist: "Fats Waller",
            img_src: IoMdMusicalNotes,
            src: Silvery,
          },
          {
            title: "Secret Garden",
            artist: "Unknown",
            img_src: IoMdMusicalNote,
            src: SecretGarden,
          },
        ],
        []
      );
    
      const playlist = useMemo(() => {
        return AudioPlaylist({
          files: songs.map((song: Song) => song.src),
          loop: false,
        });
      }, [songs]);
    
      playlist.on("start", (param) => {
        // doesn't seem to have any data in the param
        console.log(param);
      });
    
      playlist.on("end", (param) => {
        // doesn't seem to work
      });
    
      const handlePlay = () => {
        playlist.play();
        setIsPlaying(true);
      };
    
      const handlePause = () => {
        playlist.pause();
        setIsPlaying(false);
      };
    
      const handleSkip = () => {
        playlist.pause();
        playlist.next();
        setIsPlaying(true);
    
        setCurrentSong(
          (currentSong) => (currentSong + 1 + songs.length) % songs.length
        );
      };
    
      const handlePrevious = () => {
        playlist.pause();
        playlist.prev();
        setIsPlaying(true);
        setCurrentSong(
          (currentSong) => (currentSong - 1 + songs.length) % songs.length
        );
      };
    
      return (
        <div
          style={{
            backgroundColor: "gray",
            display: "flex",
            justifyContent: "space-between",
            paddingLeft: 20,
            paddingTop: 8,
          }}
        >
          <div>
            <h3>Now Playing</h3>
            <p>
              {songs[currentSong].title} by {songs[currentSong].artist}
            </p>
          </div>
    
          <div>
            <IoMdSkipBackward
              style={{ cursor: "pointer", margin: 12 }}
              onClick={handlePrevious}
            />
            {isPlaying ? (
              <IoMdPause
                style={{ cursor: "pointer", margin: 12 }}
                onClick={() => (!isPlaying ? handlePlay() : handlePause())}
              />
            ) : (
              <IoMdPlay
                style={{ cursor: "pointer", margin: 12 }}
                onClick={() => (!isPlaying ? handlePlay() : handlePause())}
              />
            )}
            <IoMdSkipForward
              style={{ cursor: "pointer", margin: 12 }}
              onClick={handleSkip}
            />
          </div>
        </div>
      );
    }
    
    
    opened by mikhael28 3
Releases(v0.7.2)
  • v0.7.2(Nov 29, 2022)

    ts-audio is an agnostic library that makes it easy to work with AudioContext and create audio playlists in the browser.

    What's new?

    • Refactored out both Audio and AudioPlaylist modules
    • Updated the AudioPlaylist module adding logic to support weighted files.
      • Note: If you pass files with a weighted structure, the playlist will be played in a loop and shuffled.
    import { AudioPlaylist } from 'ts-audio';
    import songOne from './1.mp3';
    import songTwo from './2.mp3';
    import songThree from './3.mp3'; 
    
    const playlist = AudioPlaylist({
     files: { [songOne]: 1, [songTwo]: 5, [songThree]: 1 },
    });
    
    playlist.play(); // `songTwo` will play five times more often than `songOne` and `songTree`
    
    Source code(tar.gz)
    Source code(zip)
  • v0.7.1(Aug 7, 2022)

    ts-audio is an agnostic library that makes it easy to work with AudioContext and create audio playlists in the browser.

    What's new?

    • audio.audioCtx: AudioContext Returns AudioContext object as read-only property

    • playlist.audioCtx: AudioContext Returns AudioContext object as read-only property from the currently playing audio

    Source code(tar.gz)
    Source code(zip)
  • v0.7.0(Mar 30, 2022)

    ts-audio is an agnostic library that makes it easy to work with AudioContext and create audio playlists in the browser.

    What's new?

    • Updated the AudioPlaylist component adding a new method:

      • playlist.toggle(): void Plays or pause the current audio
    • Updated the Audio component adding a new method:

      • audio.toggle(): void Plays or pause the current audio
    • Improved the preload solution performance

    • Improved unit tests

    Source code(tar.gz)
    Source code(zip)
  • v0.6.1(Dec 14, 2021)

    ts-audio is an agnostic library that makes it easy to work with AudioContext and create audio playlists in the browser.

    What's new?

    • Updated the AudioPlaylist component adding two new parameters:

      • preload?: boolean (false by default) Load the files before the play method is called

      • preloadLimit?: number (3 by default) Defines the maximum number of files that will be requested concurrently

    • Updated the Audio component adding a new parameter:

      • preload?: boolean (false by default) Load the files before the play method is called
    • Improved types

    • Improved unit tests

    Source code(tar.gz)
    Source code(zip)
  • v0.6.0(Aug 5, 2021)

    ts-audio is an agnostic library that makes it easy to work with AudioContext and create audio playlists in the browser.

    What's new?

    • Fixed bug on AudioPlaylist looping logic
    • Improved types
    Source code(tar.gz)
    Source code(zip)
  • v0.5.0(Jun 2, 2021)

    ts-audio is an agnostic library that makes it easy to work with AudioContext and create audio playlists in the browser.

    What's new?

    • Updated AudioPlaylist component adding a new optional parameter:

      • shuffle?: boolean (false by default) Shuffles the order of all files passed by parameter before playing them.
    • Complete example

    Source code(tar.gz)
    Source code(zip)
  • v0.4.7(Mar 5, 2021)

    ts-audio is an agnostic library that makes it easy to work with AudioContext and create audio playlists in the browser.

    What's new?

    • Updated AudioPlaylist component adding two new methods:

      • playlist.next(): void Stops the current audio and starts playing the next one based in the list provided in the AudioPlaylist instance. In case the current audio is the last in the list, it starts playing the first one.

      • playlist.prev(): void Stops the current audio and starts playing the previous one based in the list provided in the AudioPlaylist instance. In case the current audio is the first in the list, it starts playing the last one.

    • Complete example

    Source code(tar.gz)
    Source code(zip)
  • v0.4.5(Oct 30, 2020)

    ts-audio is an agnostic and easy-to-use library to work with the AudioContext API.

    What's new?

    • Added logic to play the audio multiple times using the same object
    • Fixed bug that played the playlist always in loop
    • Refactored code
    Source code(tar.gz)
    Source code(zip)
  • v0.4.2(Jul 26, 2020)

    ts-audio is an agnostic and easy-to-use library to work with the AudioContext API.

    What's new?

    import { AudioPlaylist } from 'ts-audio';
    
    const playlist = AudioPlaylist({
      files: ['./songOne.mp3', './songTwo.mp3', './songThree.mp3'],
      volume: 0.7,
      loop: true
    });
    
    playlist.play();
    playlist.volume; // 0.7
    playlist.volume = 05
    
    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(Jul 13, 2020)

    ts-audio is an agnostic and easy-to-use library to work with the AudioContext API.

    What's new?

    • Created AudioPlaylist component. To see more details, check our documentation.
    import { AudioPlaylist } from 'ts-audio';
    
    const playlist = AudioPlaylist({
      files: ['./songOne.mp3', './songTwo.mp3', './songThree.mp3'],
      volume: 0.7,
    });
    
    playlist.play();
    
    • Updated examples, adding a complete example of how to use AudioPlaylist
    • Created end event to Audio component. For more details, see our documentation.
    Source code(tar.gz)
    Source code(zip)
Owner
Evandro Leopoldino Gonçalves
senior learner 🤓
Evandro Leopoldino Gonçalves
A Javascript library for working with Audio. It provides a consistent API for loading and playing audio on different browsers and devices. Currently supports WebAudio, HTML5 Audio, Cordova / PhoneGap, and a Flash fallback.

SoundJS SoundJS is a library to make working with audio on the web easier. It provides a consistent API for playing audio in different browsers, inclu

CreateJS 4.3k Dec 31, 2022
It is a discord bot bot which can play lofi song in different language 24/7. It has premium system and cool embed looks with buttons. It can play youtube songs, playlists. This bot code was made by Supreme#2401. It uses djs V12

Lofi-Radio-Music-Bot It is a discord bot bot which can play lofi song in different language 24/7. It has premium system and cool embed looks with butt

Diwas Atreya 89 Jan 2, 2023
Add some fire to your Spotify music playlists 🔥🎧

Spotifire ?? Add some fire to your Spotify music playlists ?? Built With Next.js React Tailwind CSS (v3.0) NextAuth Recoil Spotify Web API Preview Vis

Niloy Sikdar 15 Jun 19, 2022
Small project to download Youtube playlists.

yt-playlist-mp3 ⚠ You must use this module respecting the YouTube's Copyright Policies. Requirements Installation Usage Install Requirements Node.js >

Matheus Filype 3 Sep 29, 2022
AmplitudeJS: Open Source HTML5 Web Audio Library. Design your web audio player, the way you want. No dependencies required.

Documentation • Examples • Tutorials • Support Us • Get Professional Help AmplitudeJS is a lightweight JavaScript library that allows you to control t

Server Side Up 3.9k Jan 2, 2023
A self-hosted, completely private and free music streaming server compatible with Synology Audio Station's web browser interface and smartphone apps.

Open Audio Server Open Audio Server is a music streaming server compatible with Audio Station by Synology. Audio Station creates your own private serv

null 91 Dec 11, 2022
create a bandcamp-style audio player for selling albums on itch.io

blamscamp Mmh, options, runnin' out of options, Mmh, options, used to have options bandcamp is great (at time of writing,) but it would be great to ha

Blackle Morisanchetto 154 Dec 21, 2022
This is a simple web based media player for playing video and audio. Build with pure HTML, CSS and Javascript. No framework or library included.

Aim-Player This is a simple web based media player for playing video and audio. Build with pure HTML, CSS and Javascript. No framework or library incl

Aim Mikel 2 Jun 27, 2021
Aviatojs - A simple library to trim, cut and join audio files.

Aviatojs A simple library to trim, cut and join audio files. Usage For a fully working example refer to this example Importing import {AviatoAudio}

null 6 Oct 7, 2022
Library to calculate a Mean Opinion Score (MOS) from 1 to 5 for audio and video real time communications

RTC SCORE Library to calculate a Mean Opinion Score (MOS) from 1 to 5 for audio and video real time communications. The first version of the algorithm

Gustavo Garcia 25 Nov 27, 2022
Easy and simple twitch bot in node.js.. very very easy..

How It Works identity: { username: 'YOUR BOTS USERNAME', <-- This is where you place the username that you gave the bot account password: '

Ventispurr 3 Dec 18, 2021
Buzz, a Javascript HTML5 Audio library

Buzz is a small but powerful Javascript library that allows you to easily take advantage of the new HTML5 audio element. It tries to degrade silently on non-modern browsers.

Jay Salvat 1.2k Dec 10, 2022
This is Kesha bot which is made for fun, to show off my appreciate to Kesha and her work

Kesha bot What is this? This is Kesha bot which is made for fun, to show off my appreciate to Kesha and her work What Kesha bot can do it is still und

Nikoloz Imerlishvili 3 Dec 15, 2022
A program that makes scripting videos easier.

A program that makes scripting videos easier. Scripts can be written using only the keyboard.

Samuel Albert 18 Jun 22, 2022
A free NodeJS sniper bot built to work with DxSale. DxLaunch is an open, decentralized platform for token sales.

DxSale sniper bot Purpose This bot allows you to compete with other trading bots when buying a cryptocurrency which is going to be on presale on DxSal

Miroslav Nedelchev 114 Dec 25, 2022
This bot can raise your mood. This bot send joke often our channel for users. Sometimes bot don't work because we have not server for this project...)

Hi, welcome to send-joke-bot telegram bot project ?? What can do this bot ? This bot can raise your mood. This bot send joke often our channel for use

Muhammadamin 5 Sep 26, 2022
An easy bot to create discord buttons easily.

Discord Buttons An easy bot to create discord buttons easily. Note: Node.js 16.6.0 or newer is required. Installation npm install You need to rename e

Fnr 7 Aug 19, 2022
HTML5

One file. Any browser. Same UI. Author: John Dyer http://j.hn/ Website: http://mediaelementjs.com/ License: MIT Meaning: Use everywhere, keep copyrigh

MediaElement.js 8k Dec 27, 2022
HTML5

One file. Any browser. Same UI. Author: John Dyer http://j.hn/ Website: http://mediaelementjs.com/ License: MIT Meaning: Use everywhere, keep copyrigh

MediaElement.js 8k Jan 8, 2023