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
77
78
#[cfg(feature = "uses_e_midi")]
pub fn init() {
// Initialize e_midi functionality here
}
#[cfg(feature = "uses_e_midi")]
use std::sync::{mpsc, Arc, atomic::{AtomicBool, Ordering}};
#[cfg(feature = "uses_e_midi")]
use std::thread;
#[cfg(feature = "uses_e_midi")]
pub struct MidiPlayerThread {
handle: thread::JoinHandle<()>,
shutdown_tx: mpsc::Sender<()>,
}
#[cfg(feature = "uses_e_midi")]
impl MidiPlayerThread {
pub fn start() -> Self {
let (shutdown_tx, shutdown_rx) = mpsc::channel();
let running = Arc::new(AtomicBool::new(true));
let running_clone = running.clone();
let handle = thread::spawn(move || {
use e_midi::MidiPlayer;
let mut player = match MidiPlayer::new() {
Ok(p) => p,
Err(e) => {
eprintln!("Failed to create MidiPlayer: {e}");
return;
}
};
let numsongs = player.get_total_song_count();
println!("Total songs: {numsongs}");
'outer: for i in 0..numsongs {
println!("Playing song {}", i + 1);
if let Err(e) = player.play_song(i, None, None) {
eprintln!("Failed to play song {}: {e}", i + 1);
continue;
}
// Wait until the song finishes or shutdown is requested
loop {
// Check for shutdown signal
if shutdown_rx.try_recv().is_ok() {
running_clone.store(false, Ordering::SeqCst);
// Stop playback immediately if playing
// if player.is_playing() {
player.stop_playback();
// }
break 'outer;
}
if !player.is_playing() {
break;
}
std::thread::yield_now();
// std::thread::sleep(std::time::Duration::from_millis(100));
}
}
// Optionally: stop playback if still playing
if player.is_playing() {
player.stop_playback();
}
});
MidiPlayerThread { handle, shutdown_tx }
}
pub fn shutdown(self) {
println!("Shutting down MidiPlayerThread...");
let _ = self.shutdown_tx.send(());
// Wait a short time to allow the thread to break out of its loop
std::thread::sleep(std::time::Duration::from_millis(200));
let _ = self.handle.join();
println!("MidiPlayerThread has shut down.");
// std::process::exit(0); // Remove this, let the main thread exit naturally
}
}