JavaScript's new Audio() method cannot play audio. How to solve it?
Solution to failed audio playback in JavaScript new Audio()
method
When playing audio using JavaScript's new Audio()
method, you often encounter the problem of failed playback. This article will analyze a common case and provide effective solutions.
In the case, the developer used new Audio()
to create an audio object, but the console reported an error uncaught (in promise) DOMException: Failed to load because no supported source was found.
, and the audio cannot be played.
The error message indicates that the browser cannot load the audio file. Combined with the code example (the HTML and JS code shown in the image are omitted here), the problem is mainly the asynchronousness of audio loading and browser security policies.
new Audio(url)
method loads the audio resource asynchronously. After the new Audio()
statement is executed, the audio is not loaded immediately, and calling music.play()
directly may cause playback failure.
Workaround: Take advantage of canplaythrough
event. This event is triggered when the audio resource can be played smoothly. Listen to the canplaythrough
event, make sure that the audio has been loaded successfully, and then call play()
method:
const music = new Audio('./1.mp3'); music.addEventListener("canplaythrough", event => { music.play(); });
This code creates an audio object and adds a canplaythrough
event listener. When the audio is loaded and playable, the listener triggers and calls music.play()
.
If it still fails to play, it may be that the browser security policy restricts automatic playback. In order to improve user experience, some browsers restrict the page from automatically playing audio without user interaction. It is recommended to add buttons to let users trigger playback manually:
const playButton = document.getElementById('playButton'); playButton.addEventListener('click', () => { music.play(); });
If the user actively triggers playback, the browser will not block the audio playback, and ensures that the audio is played successfully while respecting the user experience.
The above is the detailed content of JavaScript's new Audio() method cannot play audio. How to solve it?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to choose cryptocurrency for short-term trading in catalog? Best Cryptocurrency List of Short-term Trading Bitcoin Avalanche Solana Dogecoin Polygon World Coin Chainlink How do emerging companies choose cryptocurrencies for short-term trading? Short-term trading refers to buying cryptocurrencies and holding them for a period of time, ranging from minutes to days. This method has a bright future, but it also has risks and takes a long time because you need to continue to pay attention to the market. But that's not all; when choosing the right cryptocurrency asset, you should also pay attention to the following points: Volatility: One of the main indicators of short-term trading success is the value of highly volatile cryptocurrencies; the higher the value, the greater the price volatility, thus creating more

Introduction Decentralized Finance (DeFi) is changing the way users interact with blockchain technology, creating seamless and flexible ways for transactions, lending and earnings creation. Solayer (LAYER) is at the heart of this change, building a protocol that connects liquidity and practicality across multiple blockchains. With the popularity of DeFi and the growing demand for efficient cross-chain infrastructure, Solayer is attracting the attention of traders, developers and investors who are looking for the next major opportunity. This article will explain the concept of Solayer, detail its innovative features and token economics, and look forward to its 2030

You don't need to be an economist to feel the economic turmoil. Prices fall, job stability declines, and everyone seems to be anxious about their financial future. What is a stablecoin? Stablecoins are like life jackets in the crypto world: a digital currency designed to keep its value stable, often linked to stable assets such as the US dollar or gold. Unlike cryptocurrencies with severe price fluctuations such as Bitcoin or Ethereum, stablecoins pursue stability. When an economic storm strikes, investors will naturally seek stability, and stablecoins just provide this safe-haven asset – free from volatility. Why stablecoins thrive when economic instability is

Table of Contents What is VitaInu (VINU)? What is VINU token? 2025 VINU Coin Price Forecast VitaInu (VINU) Price Forecast 2025-2030 to 2030 VitaInu (VINU) Price Forecast 2025 VitaInu Price Forecast 2026 VitaInu Price Forecast 2027 VitaInu Price Forecast 2028 VitaInu Price Forecast 2029 VitaInu Price Forecast 2030 VitaInu Price Forecast Interpretation of VINU’s Market Performance

In today's digital economy, the boundaries between traditional finance and blockchain technology are beginning to blur. People are eager for faster payments, borderless transactions and more control over their own funds – and they are eager to achieve it immediately. ZebecNetwork is one of many projects aimed at meeting this need by building programmable fund flow infrastructure. Focusing on real-time payroll, crypto payments and decentralized systems, Zebec positiones itself as a bridge connecting mature financial practices with emerging blockchain solutions. This article outlines ZebecNetwork – it

The two major Meme coins on Solana's chain, MooDeng (MOODENG) and GoatseusMaximus (GOAT), quickly turned popular after landing on Binance's "Alpha" platform yesterday (11), rekindling investors' enthusiasm. The price of MOODENG coins soared by more than 123% in a single day, setting a new high this year. Binance Alpha mainly focuses on early potential currencies, and usually lists currencies with high social popularity and growth potential. Now it has officially launched MOODENG and GOAT, which not only injects lively water into these two Meme coins, but also allows the Solana ecosystem to be reborn.

Blockchain technology continues to change the way people exchange value, verify information and build trust online. As decentralized applications flourish in various industries, the ability to confirm statements and identities across multiple blockchains has become increasingly important and complex. Traditional trust models that rely on centralized authority are often insufficient to support a decentralized ecosystem, so the demand for blockchain native verification solutions is also growing. SignProtocol (SIGN) addresses this challenge by providing a framework for creating, verifying, and managing proofs across multiple blockchain networks. SignProtocol aims to create a full chain

Cryptocurrency market projects have emerged with the development of blockchain, with the purpose of changing traditional financial practices, and SwissCheese is one of them. It is understood that SwissCheese is a decentralized platform that allows users to trade tokenized stocks, aiming to enhance market access and reduce transaction costs, paving the way for a more inclusive financial environment. The native token of the platform is SWCH, and its main functions are transactions, governance, etc. The project immediately attracted investors' attention after it went online, but only know what currency is SWCH? Can't we analyze that SWCH is worth investing in? Based on the current data, SWCH has a certain
