« get me outta code hell

loop-play.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/loop-play.js
blob: 5205025377bbec364d858aee8d0c7794253f7bf3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict'

const fs = require('fs')
const tempy = require('tempy')

const { spawn } = require('child_process')
const { promisify } = require('util')
const fetch = require('node-fetch')
const path = require('path')
const promisifyProcess = require('./promisify-process')
const sanitize = require('sanitize-filename')

const writeFile = promisify(fs.writeFile)

module.exports = async function loopPlay(picker, downloader, playArgs = []) {
  // Looping play function. Takes one argument, the "pick" function,
  // which returns a track to play. Preemptively downloads the next
  // track while the current one is playing for seamless continuation
  // from one song to the next. Stops when the result of the pick
  // function is null (or similar). Optionally takes a second argument
  // used as arguments to the `play` process (before the file name).

  async function downloadNext() {
    const picked = picker()

    if (picked == null) {
      return false
    }

    const [ title, downloaderArg ] = picked
    console.log(`Downloading ${title}..\nDownloader arg: ${downloaderArg}`)

    const downloadFile = await downloader(downloaderArg)

    const tempDir = tempy.directory()
    const wavFile = tempDir + `/.${sanitize(title)}.wav`

    try {
      await convert(downloadFile, wavFile)
    } catch(err) {
      console.warn("Failed to convert " + title)
      console.warn("Selecting a new track\n")

      return await downloadNext()
    }

    return wavFile
  }

  let wavFile = await downloadNext()

  while (wavFile) {
    const nextPromise = downloadNext()
    await playFile(wavFile, playArgs)
    wavFile = await nextPromise
  }
}

function convert(fromFile, toFile) {
  const avconv = spawn('avconv', ['-y', '-i', fromFile, toFile])
  return promisifyProcess(avconv, false)
}

function playFile(file, opts = []) {
  const play = spawn('play', [...opts, file])
  return promisifyProcess(play)
}