如何使用 JavaScript 实现一个简单的音频播放功能? - 项越资源网-html css js 用法分享社区-开发交流-项越资源网

如何使用 JavaScript 实现一个简单的音频播放功能?

这是遵循HTML音频标准的最简单的方式:

<audio id="player" src="https://example.com/path/to/audio.mp3" type="audio/mpeg">
</audio>

<button onclick="document.getElementById('player').play()">
  Play
</button>
<button onclick="document.getElementById('player').pause()">
  Pause
</button>

也可以使用JavaScript完全控制播放音频:

// Get an audio element
const audio = document.getElementById('player');

// Initialize the audio context
const context = new AudioContext();

// Load the audio file into the audio context
const source = context.createBufferSource();
source.buffer = await context.decodeAudioData(audioFile);

// Connect the audio node to the speakers
source.connect(context.destination);

// Start playing the sound
source.start();
请登录后发表评论

    没有回复内容