Playing mp3s From the File System in Mono (C#) Godot

November 12, 2021

One of the new features in Godot 3.3 is playing mp3s, with built-in engine support. I was excited to try out this feature. However, most of the guides were assuming you'd be bundling the mp3s as a resource in the Godot project. For my project, we wanted to be able to play mp3s that were on the file system and not shipped with our game. One use case of this is playing mp3s that are part of a third-party mod.

It took some time to figure out how to do this. Eventually, I found a post where someone discussed implementing this in GDScript, which gave enough information to figure out the key parts for a C# version. Without further ado, here is the code in C#:

public class MP3MusicPlayer : AudioStreamPlayer
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
		string mp3Path = "PathToMp3File.mp3";	//Probably will want to make this dynamic in your program
		File mp3File = new File();
		mp3File.Open(mp3Path, Godot.File.ModeFlags.Read);

		AudioStreamMP3 mp3 = new AudioStreamMP3();
		long fileSize = (long)mp3File.GetLen();	//GetBuffer needs signed long; file length returns unsigned long.
		mp3.Data = mp3File.GetBuffer(fileSize);
		mp3.Loop = true;

		this.Stream = mp3;

		this.Play();	//Will cause it to play as soon as the Node enters the scene; you may not want this

It's a little trickier than I'd first expected, but once you've figured it out it isn't too much code. Hopefully this post made it easier for you to implement mp3 support in your Mono Godot project as well.

Return to Blog Index