你能在discord.js资源中从URL流式传输音频吗



如何使用discord.js v13从url播放音频。

我使用了这个代码,但它不起作用。

const connection = joinVoiceChannel({
channelId: channel_id.id,
guildId: guild_id,
adapterCreator: message.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
const resource = createAudioResource('http://radioplayer.kissfmuk.com/live/')
player.play(resource)
connection.subscribe(player)

我已经激活了所有意向,机器人显示一个绿色圆圈,但没有音频播放。你知道它是怎么工作的吗?

您试图创建其资源的链接必须返回音频文件。实时音频广播将无法使用您当前的代码。如果url给你一个.mp3文件,那么代码应该可以工作。

示例功能:

const Discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES] });
const config =  require('./config/config.json');
const { joinVoiceChannel, createAudioPlayer, NoSubscriberBehavior, createAudioResource, AudioPlayerStatus, VoiceConnectionStatus, entersState } = require('@discordjs/voice');
const { join } = require('path');
client.once('ready', () => {
console.log(config.onlineMessage);
const channels = client.guilds.cache.find(f => f.name==="<Server Name>").channels;
JoinChannel(channels.cache.find(r => r.name === "<Channel Name>"), './background.mp3', 0.025);  
});
client.login(config.token);
function JoinChannel(channel, track, volume) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guildId,
adapterCreator: channel.guild.voiceAdapterCreator,
});
const player = createAudioPlayer();
resource = createAudioResource(join(__dirname, track), { inlineVolume: true });
resource.volume.setVolume(volume);
connection.subscribe(player); 
connection.on(VoiceConnectionStatus.Ready, () => {console.log("ready"); player.play(resource);})
connection.on(VoiceConnectionStatus.Disconnected, async (oldState, newState) => {
try {
console.log("Disconnected.")
await Promise.race([
entersState(connection, VoiceConnectionStatus.Signalling, 5_000),
entersState(connection, VoiceConnectionStatus.Connecting, 5_000),
]);
} catch (error) {
connection.destroy();
}
});
player.on('error', error => {
console.error(`Error: ${error.message} with resource ${error.resource.metadata.title}`);
player.play(getNextResource());
});
player.on(AudioPlayerStatus.Playing, () => {
console.log('The audio player has started playing!');
}); 
player.on('idle', () => {
connection.destroy();
})
}

答案很简单,我只需要在播放资源之前订阅连接!

const connection = joinVoiceChannel({
channelId: channel_id.id,
guildId: guild_id,
adapterCreator: message.guild.voiceAdapterCreator,
});

const resource = 
createAudioResource('https://streams.ilovemusic.de/iloveradio8.mp3', {
inlineVolume: true
})
const player = createAudioPlayer();
connection.subscribe(player)
player.play(resource)

最新更新