이 페이지는 현재 영어로만 제공되며 한국어 버전은 곧 제공될 예정입니다. 기다려 주셔서 감사드립니다.
Feedback

오디오 믹싱 활성화

Feature Description

This article introduces how to use the AudioPlayer plugin to implement background music during a call. The AudioPlayer plugin supports playing audio files in mp3, ogg, wav, and flac formats, and can mix the audio into the publishing stream to push it to remote users.
Compared to the AudioMixer plugin, the AudioPlayer plugin provides an instance-based playback control approach, supporting more flexible playback controls (start/pause/resume/stop/seek) and dynamic property modifications.

Demo



Prerequisites

TRTC version 5.18.0+
The following platforms support adding background music during a call:
Operating System
Browser Type
Minimum Browser Version
Mac OS
Desktop Chrome
56+
Desktop Safari
11+
Desktop Firefox
56+
Desktop Edge
80+
Windows
Desktop Chrome
56+
Desktop QQ Browser
10.4+
Desktop Firefox
56+
Desktop Edge
80+
iOS
Mobile Safari
16+
WeChat Embedded Web
✖
Android
Mobile Chrome
81+
WeChat Embedded Web
✔
Mobile QQ Browser
✖

Implementation Process

Start Background Music

Note:
When playing online sound effect files, the sound effect files must support CORS and the access protocol must be https.
Supported formats include MP3, AAC (and other audio formats supported by browsers).
When using publish: true, you need to enter the room and publish audio stream first (call trtc.startLocalAudio()), ensure local audio is published before creating the player.
Before any user interaction, browsers prohibit web pages from playing media with sound. It is recommended to guide users to perform a click action before calling this interface.
Reference: Autoplay_guide.

1. Install and Register Plugin

import TRTC from 'trtc-sdk-v5';
import AudioPlayer from 'trtc-sdk-v5/plugins/audio-player';

const trtc = TRTC.create({ plugins: [AudioPlayer] });

2. Enter Room and Enable Microphone

await trtc.enterRoom({ roomId: 8888, sdkAppId, userId, userSig });
await trtc.startLocalAudio();

3. Create Player and Play Background Music

Use trtc.startPlugin to create a URL player instance, set publish: true to mix the audio into the published stream and send to remote users.
const player = await trtc.startPlugin('AudioPlayer', {
id: 'bgm',
sourceType: 'url',
url: 'https://example.com/music.mp3',
loop: true,
volume: 0.5,
publish: true,
onTimeUpdate: (currentTime, duration) => {
console.log(`Playback progress: ${currentTime.toFixed(2)}s / ${duration.toFixed(2)}s`);
},
onDurationChange: (duration) => {
console.log(`Audio duration: ${duration.toFixed(2)}s`);
},
onEnded: () => {
console.log('Playback ended');
},
});

// Start playback
await player.start();

4. Control Player

Control playback through player instance methods:
// Pause playback
player.pause();

// Resume playback
player.resume();

// Seek to specified time (seconds)
player.seek(30);

// Stop playback (reset to beginning)
player.stop();

// Restart playback
await player.start();
Dynamically modify parameters through instance properties:
// Adjust volume (0~1)
player.volume = 0.8;

// Toggle loop playback
player.loop = false;

// Adjust playback rate
player.playbackRate = 1.5;

// Dynamically toggle whether to send to remote users
player.publish = false;

5. Destroy Player

When the player is no longer needed, call stopPlugin to destroy it:
// Destroy specific player
await trtc.stopPlugin('AudioPlayer', { id: 'bgm' });
player = null; // Actively release reference to avoid memory leaks

// Destroy all players
await trtc.stopPlugin('AudioPlayer', { id: '*' });
Important:
After calling stopPlugin to destroy the player, be sure to set the player instance reference to null, otherwise the instance object cannot be garbage collected, causing memory leaks.

API Reference

trtc.startPlugin('AudioPlayer', options)

Create an audio player instance.

options

Parameter
Type
Required
Default
Description
id
string
✅
-
Player instance unique identifier
sourceType
string
✅
-
Audio source type, set to 'url'
url
string
✅
-
Audio file URL, supports mp3/ogg/wav/flac formats and blob/data URLs
publish
boolean
❌
false
Whether to mix into published stream and send to remote users
loop
boolean
❌
false
Whether to loop playback
volume
number
❌
1
Playback volume (0~1)
playbackRate
number
❌
1
Playback rate
onTimeUpdate
function
❌
-
Playback progress callback, parameters: (currentTime: number, duration: number) in seconds
onDurationChange
function
❌
-
Audio duration change callback, parameter: (duration: number) in seconds
onEnded
function
❌
-
Playback end callback (not triggered at each loop end in loop mode)
Return value: Promise<AudioPlayerContext> — Player instance
Example:
const player = await trtc.startPlugin('AudioPlayer', {
id: 'bgm',
sourceType: 'url',
url: 'https://example.com/music.mp3',
loop: true,
volume: 0.5,
playbackRate: 1.0,
publish: true,
onTimeUpdate: (currentTime, duration) => {
console.log(`${currentTime}s / ${duration}s`);
},
onDurationChange: (duration) => {
console.log(`Audio duration: ${duration}s`);
},
onEnded: () => {
console.log('Playback ended');
},
});

Player Instance Methods

Method
Description
start()
Start playback, returns Promise
pause()
Pause playback
resume()
Resume playback from paused position
stop()
Stop playback, reset to beginning
seek(time)
Seek to specified time (seconds)

Player Instance Read-only Properties

Property
Type
Description
id
string
Player instance ID
sourceType
string
Audio source type
currentTime
number
Current playback time (seconds)
duration
number
Audio total duration (seconds)
isStop
boolean
Whether stopped
isPause
boolean
Whether paused
isPlayEnd
boolean
Whether playback ended

Player Instance Read-write Properties

Property
Type
Description
volume
number
Playback volume (0~1)
loop
boolean
Whether to loop playback
playbackRate
number
Playback rate
publish
boolean
Whether to mix into published stream

trtc.stopPlugin('AudioPlayer', options)

Destroy player instance.

options

Parameter
Type
Description
id
string
Target player instance ID, pass '*' to destroy all instances
Example:
// Destroy specific player
await trtc.stopPlugin('AudioPlayer', { id: 'bgm' });

// Destroy all players
await trtc.stopPlugin('AudioPlayer', { id: '*' });

// Release player reference
player = null;
Important:
After calling stopPlugin to destroy the player, be sure to set the player instance reference to null, otherwise the instance object cannot be garbage collected, causing memory leaks.

Common Issues

Cross-origin error occurs

Example: Access to audio at XXX from origin XXX has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Solution: You need to configure CORS protocol for online music files, ensuring the audio resource server allows cross-origin access.

Audio format not supported

Example: NotSupportedError: The operation is not supported.
Solution: Please use browser-supported audio formats (recommended mp3, aac, ogg, wav, flac).

publish set to true but remote users cannot hear

Solution: When using publish: true, you need to enter the room and publish audio stream first (call trtc.startLocalAudio()), ensure local audio is published before creating the player.

Cannot play on iOS devices

Solution: iOS browsers require audio playback to be triggered by user gestures, ensure player.start() is called within user click event callbacks.

How to play multiple background music simultaneously

AudioPlayer supports multi-instance management, create multiple players with different ids:
const bgm1 = await trtc.startPlugin('AudioPlayer', {
id: 'bgm1',
sourceType: 'url',
url: 'https://example.com/music1.mp3',
publish: true,
});

const bgm2 = await trtc.startPlugin('AudioPlayer', {
id: 'bgm2',
sourceType: 'url',
url: 'https://example.com/music2.mp3',
publish: true,
});

await bgm1.start();
await bgm2.start();