R/write_subtitles.R

Defines functions write_subtitles

Documented in write_subtitles

#' Write subtitles
#'
#' This function writes a \code{subtitles} object in a file.
#'
#' @param x an object of class \code{subtitles}.
#' @param file a character string naming a file for writing.
#' @param format a character string giving the file format.
#' Not used (only SubRip format is currently implemented).
#' @param encoding the name of the encoding to be used.
#'
#' @returns Called for its side effects (writing to \code{file}). Returns \code{NULL} invisibly.
#'
#' @export
#'
write_subtitles <- function(x, file, format = "srt", encoding = "UTF-8") {
  if (!is(x, "subtitles")) {
    stop("x must be a 'subtitles' object.")
  }
  dir <- dirname(file)
  if (!file.exists(dir) || file.access(dir, mode = 2) != 0) {
    stop("'file' must be in a writable location.")
  }
  tc <- paste(x$Timecode_in, x$Timecode_out, sep = " --> ")
  tc <- gsub("\\.", ",", tc)
  res <- paste(x$ID, tc, x$Text_content, sep = "\n", collapse = "\n\n")

  con <- file(file, encoding = encoding)
  writeLines(res, con)
  close(con)
}

Try the subtools package in your browser

Any scripts or data that you put into this service are public.

subtools documentation built on March 24, 2026, 5:07 p.m.