summaryrefslogtreecommitdiffhomepage
path: root/AudioPlayer.cpp
blob: e60ae1d58eb8f6aae876b691daf32818c760adf6 (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
#include "AudioPlayer.h"

#include <iostream>

#include <fmt/format.h>

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

AudioPlayer::AudioPlayer(const fs::path& dir, const std::string& filename): m_dir(dir), m_file(filename)
{
}

void AudioPlayer::start()
{
  if (m_child_audioplayer.valid() && m_child_audioplayer.running()) {
    stop();
  }
  if (!m_file.empty()) {
    m_child_audioplayer = bp::child(fmt::format("aplay \"{}\"", (m_dir / m_file).string()).c_str());//, bp::std_out > bp::null);
    if (!m_child_audioplayer.valid() || !m_child_audioplayer.running()) {
      throw std::runtime_error("aplay not started");
    }
  }
}

void AudioPlayer::stop()
{
  // note:: m_child_audioplayer.terminate() would kill via SIGKILL

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

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