Skip to content

Instantly share code, notes, and snippets.

@rosalogia
Created November 28, 2021 22:19
Show Gist options
  • Save rosalogia/bf0f3ede229a9c6552138db86e2ea5e7 to your computer and use it in GitHub Desktop.
Save rosalogia/bf0f3ede229a9c6552138db86e2ea5e7 to your computer and use it in GitHub Desktop.
Simple example of using OCaml taglib bindings to get and set tags on an audio file
(* Make sure you have taglib installed. Find complete
documentation at https://github.com/savonet/ocaml-taglib/blob/master/src/taglib.mli *)
(* We write a small program that either displays or modifies a given
tag for a given audio file.
Usage example:
./main.exe get artist my_song.mp3
or
./main.exe set artist BikaBika my_song.mp3 *)
let () =
let action = Sys.argv.(1) in (* Should be "get" or "set" *)
let tag = Sys.argv.(2) in (* Should be "album", "title", "track", "year", "genre", "comment", or "artist" *)
(* If action is "set", then Sys.argv.(3) should be the value that the tag is being set to *)
let file_path = if action = "set" then Sys.argv.(4) else Sys.argv.(3) in
let taglib_file = Taglib.File.open_file `Autodetect file_path in (* Actually loads up the file with taglib *)
(match tag with
| "album" ->
(match action with
| "get" -> print_endline (Taglib.tag_album taglib_file)
| "set" -> Taglib.tag_set_album taglib_file Sys.argv.(3)
| _ -> failwith "Action invalid")
| "title" ->
(match action with
| "get" -> print_endline (Taglib.tag_title taglib_file)
| "set" ->
Taglib.tag_set_title taglib_file Sys.argv.(3);
Taglib.File.file_save taglib_file |> ignore
| _ -> failwith "Action invalid")
| "track" ->
(match action with
| "get" -> Printf.printf "%d\n" (Taglib.tag_track taglib_file)
| "set" -> Taglib.tag_set_track taglib_file (int_of_string Sys.argv.(3))
| _ -> failwith "Action invalid")
| "year" ->
(match action with
| "get" -> Printf.printf "%d\n" (Taglib.tag_year taglib_file)
| "set" -> Taglib.tag_set_year taglib_file (int_of_string Sys.argv.(3))
| _ -> failwith "Action invalid")
| "genre" ->
(match action with
| "get" -> print_endline (Taglib.tag_genre taglib_file)
| "set" -> Taglib.tag_set_genre taglib_file Sys.argv.(3)
| _ -> failwith "Action invalid")
| "comment" ->
(match action with
| "get" -> print_endline (Taglib.tag_comment taglib_file)
| "set" -> Taglib.tag_set_comment taglib_file Sys.argv.(3)
| _ -> failwith "Action invalid")
| "artist" ->
(match action with
| "get" -> print_endline (Taglib.tag_artist taglib_file)
| "set" ->
Printf.printf "Setting artist of file %s to %s\n" file_path Sys.argv.(3);
Taglib.tag_set_artist taglib_file Sys.argv.(3)
| _ -> failwith "Action invalid")
| _ -> print_endline "Tag invalid");
(* This is where we save the changes we've made to the actual file *)
Taglib.File.file_save taglib_file |> ignore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment