Last active
November 1, 2022 22:14
-
-
Save lambdan/55fbd2c37d0e6e4d91dde67deb01cff5 to your computer and use it in GitHub Desktop.
yt-dlp audio download in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Requires yt-dlp.exe in %PATH% !! | |
using System.Collections; | |
using UnityEngine; | |
using UnityEngine.Events; | |
using UnityEngine.Windows; | |
public class IllegalScript : MonoBehaviour | |
{ | |
private string savefolder; | |
private string current_url; | |
public AudioSource _audioSource; | |
public UnityEvent downloadComplete; | |
public UnityEvent audioLoaded; | |
string youtubeID (string url) | |
{ | |
return url.Split("?v=")[1].Split("&")[0]; | |
} | |
void Start() | |
{ | |
savefolder = Application.persistentDataPath; // %appdata%/LocalLow/Company/ProjectName | |
downloadComplete.AddListener(LoadAudio); | |
audioLoaded.AddListener(PlayAudio); | |
} | |
public void Download(string url) | |
{ | |
current_url = url; | |
string path_to_audio = savefolder + "/" + youtubeID(current_url) + ".mp3"; | |
if (!File.Exists(path_to_audio)) | |
{ | |
StartCoroutine(ActuallyDownload(url, path_to_audio)); | |
} | |
else | |
{ | |
downloadComplete.Invoke(); // Already had it, dont need to download | |
} | |
} | |
public void LoadAudio() | |
{ | |
StartCoroutine(LoadAudioCoroutine(savefolder + "/" + youtubeID(current_url) + ".mp3")); | |
} | |
public void PlayAudio() | |
{ | |
_audioSource.Play(); | |
} | |
IEnumerator ActuallyDownload(string url, string output) | |
{ | |
string cmd = url + " --no-playlist --force-overwrites --audio-format mp3 -x -o " + output; | |
var a = System.Diagnostics.Process.Start("yt-dlp.exe", cmd); | |
while (!a.HasExited) | |
{ | |
yield return new WaitForSeconds(0.1f); | |
} | |
downloadComplete.Invoke(); | |
} | |
IEnumerator LoadAudioCoroutine(string path) | |
{ | |
WWW request = new WWW(path); | |
yield return request; | |
_audioSource.clip = request.GetAudioClip(); | |
audioLoaded.Invoke(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment