summaryrefslogtreecommitdiffhomepage
path: root/MIDIPlayer.cpp
blob: c7945d6e2fad39416c240bfbbe4b9f501e372f1a (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
68
69
70
71
72
73
74
75
76
#include "MIDIPlayer.h"

#include <signal.h>

#include <iostream>

namespace bp = boost::process;
namespace fs = std::filesystem;

MIDIPlayer::MIDIPlayer(const std::filesystem::path& path):
  m_child{},
  m_dir{path},
  m_file{}
{
  std::vector<std::string> list = get_filelist();

  if (list.size() > 0) {
    m_file = list[0];
  }
}

void MIDIPlayer::start()
{
  if (m_child.valid() && m_child.running()) {
    stop();
  } else {
    m_child = bp::child("aplaymidi -p24 locked_out_of_heaven.midi");//, bp::std_out > bp::null);
  }
}

void MIDIPlayer::stop()
{
  // note:: m_child.terminate() would kill via SIGKILL, preventing note offs

  if (m_child.valid()) {
    int result = kill(m_child.native_handle(), SIGTERM);
    if (result < 0) {
      std::cerr << "Error in MIDIPlayer::stop(): kill() unsuccessful\n";
    }
  }
}

bool MIDIPlayer::is_playing()
{
  if (!m_child.valid()) {
    return false;
  }
  return m_child.running();
}

void MIDIPlayer::set_file(const std::string& filename)
{
  m_file = filename;
}

std::string MIDIPlayer::get_file()
{
  return m_file;
}

std::vector<std::string> MIDIPlayer::get_filelist()
{
  std::vector<std::string> result;
  for (auto const& dir_entry: fs::directory_iterator{m_dir}) {
    fs::path entry{dir_entry.path()};
    fs::path extension = entry.extension();
    if (extension == ".midi" || extension == ".mid") {
      result.push_back(entry.filename());
    }
    if (result.size() == 99) {
      break;
    }
  }
  return result;
}