preface

Hello everyone, today brings you a based on anyRTC Web SDK to play network audio or local audio files function.

The premise condition

There are a few things you need to do before you start writing code. If you haven’t used the anyRTC Web SDK before, take a few minutes to prepare

Operation process

configuration

const config = {
    appid: appid, // Enter the appID obtained in the previous "prerequisites" section
    channel: '505050'./ / channel number
    uid: 'web' + Math.floor(Math.random() * 2021428) // Randomly generated user ID
};
var client = null; // Local client object
Copy the code

Get DOM node

const urlButton = document.getElementsByTagName('span') [0];
const fileButton = document.getElementsByTagName('span') [1];
const urlInput = document.getElementsByTagName('input') [0];
const fileInput = document.getElementsByTagName('input') [1];
const join = document.getElementsByTagName('p') [0];
Copy the code

Bind click events

// Network audio
urlButton.onclick = () = > {
    // http://music.163.com/song/media/outer/url?id=1811921555.mp3
    // In order to save your time, I have prepared a network audio resource for you
    // You can put the above link in the browser address bar to visit, and then the browser address bar will change
    // Then copy the changed browser address into the input box
    const source = urlInput.value;
    if (source) {
        publishAndPlay(source);
    } else {
        alert('Please enter the network MP3 link'); }};// Local audio file
fileButton.onclick = () = > {
    const source = fileInput.files[0];
    if (source) {
        publishAndPlay(source);
    } else {
        alert('Please select audio file'); }};// The room joining logic could have been done automatically when initialized
// But Google Chrome doesn't allow audio to play automatically (you have to interact with the page to play), so click to join the room is added;
// This is for remote users to play automatically
join.onclick = () = > {
    const { appid, channel, uid } = config;
    // Join the channel
    client.join(appid, channel, null, uid).then(() = > {
        // Some style manipulation
        urlButton.parentNode.style.display = 'flex';
        fileButton.parentNode.style.display = 'flex';
        join.style.display = 'none';
    }, () = > {
        alert('Failed to join room');
    });
};
Copy the code

Methods the function

const publishAndPlay = async (source) => {
    const bufferAudioOptions = {source};
    // Create an audio track from an audio file or AudioBuffer object.
    const track = await ArRTC.createBufferSourceAudioTrack(bufferAudioOptions);
    // Play audio locally (mandatory)
    track.play();
    // Start the process audio buffer (required)
    track.startProcessAudioBuffer();
    // Publish to channel (at this point both remote users (make sure they have joined the channel) and local users can hear the sound)
    client.publish(track);
};
Copy the code

Project initialization

const init = () = > {
    client = ArRTC.createClient({ mode: "rtc".codec: "h264" });
    // Listen for users to publish audio and video streams
    client.on("user-published".async (user, mediaType) => {
        await client.subscribe(user, mediaType);
        if (mediaType === 'audio') { user.audioTrack.play(); }}); }; init();Copy the code

The complete code is as follows

At this point, the function of playing network audio or local audio files is complete, interested partners can copy the code below to see the operation effect, if you like this article or want to continue to pay attention to the latest technology trends of anyRTC, you can follow me oh;

HTML part

<div class='main'>
    <p class='join'>To join the room</p>
    <div class='url-box'>
        <input type="text" placeholder="Enter the mp3 link from the web.">
        <span class='button'>Collecting audio</span>
    </div>
    <div class='file-box'>
        <input type="file">
        <span class='button'>Collecting audio</span>
    </div>
</div>
<script src="/<YOUR_PATH>/to/[email protected]"></script>
<script src="index.js"></script>
Copy the code

The CSS part

.main {
    display: flex;
    justify-content: space-between;
    width: 500px;
    margin: 50px auto;
}

.main .join {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 100px;
    line-height: 34px;
    border-radius: 4px;
    text-align: center;
    color: #fff;
    font-size: 12px;
    background-color: #409EFF;
    cursor: pointer;
    transform: translate(-50px, -17px);
    transition:.3s;
}

.main .join:hover {
    background-color: #66B1FF;
}

.main .url-box..file-box {
    display: none;
    height: 80px;
    justify-content: space-between;
    flex-direction: column;
    margin-bottom: 40px;
}

.main .button {
    display: inline-block;
    width: 80px;
    line-height: 26px;
    border-radius: 2px;
    text-align: center;
    color: #fff;
    font-size: 12px;
    background-color: #409EFF;
    cursor: pointer;
}
Copy the code

Javascript part

const urlButton = document.getElementsByTagName('span') [0];
const fileButton = document.getElementsByTagName('span') [1];
const urlInput = document.getElementsByTagName('input') [0];
const fileInput = document.getElementsByTagName('input') [1];
const join = document.getElementsByTagName('p') [0];

const config = {
    appid: ' '.channel: '505050'.uid: 'web' + Math.floor(Math.random() * 2021428)};var client = null;

urlButton.onclick = () = > {
    const source = urlInput.value;
    if (source) {
        publishAndPlay(source);
    } else {
        alert('Please enter the network MP3 link'); }}; fileButton.onclick =() = > {
    const source = fileInput.files[0];
    if (source) {
        publishAndPlay(source);
    } else {
        alert('Please select audio file'); }}; join.onclick =() = > {
    const { appid, channel, uid } = config;
    client.join(appid, channel, null, uid).then(() = > {
        urlButton.parentNode.style.display = 'flex';
        fileButton.parentNode.style.display = 'flex';
        join.style.display = 'none';
    }, () = > {
        alert('Failed to join room');
    });
};

const publishAndPlay = async (source) => {
    const bufferAudioOptions = {source};
    const track = await ArRTC.createBufferSourceAudioTrack(bufferAudioOptions);
    track.play();
    track.startProcessAudioBuffer();
    client.publish(track);
};

const init = () = > {
    client = ArRTC.createClient({ mode: "rtc".codec: "h264" });
    client.on("user-published".async (user, mediaType) => {
        await client.subscribe(user, mediaType);
        if (mediaType === 'audio') { user.audioTrack.play(); }}); }; init();Copy the code