也有有段时间没写godot了,今天这个是通过插件实现一个在线电台播放器。插件看起来也不复杂。
插件地址:https://github.com/jefvaia/Godot-WebRadio
为了获取到消息,插件中webradiostreamplayer.gd这三个文件需要稍作修改。主要是添加一个buffer_ready信号。
extends AudioStreamPlayer
class_name WebRadioStreamPlayer
signal buffer_ready
@export var url: String
func _ready() -> void:
var http_instance = WebRadioStreamHelper.get_radio(url)
if http_instance == null:
http_instance = WebRadioStreamHelper.add_radio(url)
if http_instance.player_done_connected == false:
self.finished.connect(http_instance.player_done)
http_instance.player_done_connected = true
http_instance.buffer_ready.connect(_refresh_stream)
func _refresh_stream(new_stream: AudioStreamMP3):
emit_signal("buffer_ready") # 触发信号
self.stream = new_stream
self.play(0)

工程中引用此插件并启用。
添加两个控件:Button和Timer。分别用于换台和换台等待效果。插件的引用是通过代码进行的。
以下是完整的场景代码,不足50行。其实Timer控件也不是必须的,只是实现一个载入等待的效果。
extends Node2D
var urls = [
"https://ytcastmp3.radio.cn/61/stream_10452.mp3?type=1&key=19f1abde8ee2e1a455ed201cc55c6bd7&time=68085997",
"https://ytcastmp3.radio.cn/61/stream_10448.mp3?type=1&key=41abbae95c096f4a128b63c856d0941b&time=6808691c",
"https://ytcastmp3.radio.cn/61/stream_10449.mp3?type=1&key=c4cbe8924a8e40bf160dcd77dbc202df&time=6808691c",
"https://ytcastmp3.radio.cn/61/stream_10450.mp3?type=1&key=366b2dd47a69d44e943ede379b67d9dc&time=6808691c",
"https://ytcastmp3.radio.cn/61/stream_10457.mp3?type=1&key=688cda7f14506cf0560555165b4bfee3&time=6808691c",
"https://ytcastmp3.radio.cn/61/stream_10445.mp3?type=1&key=9623004423973c09fe9bc7035015b83d&time=680869a3",
]
var dot_count := 0 # 记录当前点数
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
pass
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
pass
func _on_button_pressed() -> void:
var url = urls[randi() % urls.size()]
print(url)
$Timer.start()
$Button.disabled = true
var wrp = WebRadioStreamPlayer.new()
wrp.url = url
wrp.name = "WebReadioPlayer1"
wrp.autoplay = true
wrp.connect("buffer_ready",buffer_ready)
add_child(wrp)
if $WebReadioPlayer!=null: # 删除原有对象
$WebReadioPlayer.stop()
$WebReadioPlayer.queue_free()
await get_tree().create_timer(1.0).timeout
wrp.name = "WebReadioPlayer"
func buffer_ready() -> void:
$Timer.stop()
$Button.disabled = false
$Button.text = "点击换台"
func _on_timer_timeout() -> void:
dot_count = (dot_count + 1) % 4
$Button.text = "载入中" + ".".repeat(dot_count)
打赏