feat: play && stop checks

This commit is contained in:
Ahmet Kaan GÜMÜŞ 2024-04-07 06:10:09 +03:00
parent eabe8e0521
commit 4b158d5195
8 changed files with 176 additions and 141 deletions

View file

@ -5,17 +5,15 @@ pub mod streaming;
pub mod utils;
#[derive(Debug, Clone)]
pub struct AppState{
}
pub struct AppState {}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
enum ServerStatus{
enum ServerStatus {
Alive,
Unstable,
Dead,
}
#[derive(Debug, Clone, PartialEq, Serialize,Deserialize)]
enum CoinStatus{
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
enum CoinStatus {
Tail,
Head,
}
}

View file

@ -1,10 +1,10 @@
use back::{AppState, routing, streaming};
use std::{env, net::SocketAddr};
use axum_server::tls_rustls::RustlsConfig;
use back::{routing, streaming, AppState};
use std::{env, net::SocketAddr};
fn take_args() -> String{
let mut bind_address:String = String::new();
for element in env::args(){
fn take_args() -> String {
let mut bind_address: String = String::new();
for element in env::args() {
bind_address = element
}
println!("\n\n\tOn Air -> http://{}\n\n", bind_address);
@ -14,13 +14,11 @@ fn take_args() -> String{
#[tokio::main]
async fn main() {
println!("Hello, world!");
let config = RustlsConfig::from_pem_file(
"certificates/fullchain.pem",
"certificates/privkey.pem"
).await.unwrap();
let state = AppState{
};
let config =
RustlsConfig::from_pem_file("certificates/fullchain.pem", "certificates/privkey.pem")
.await
.unwrap();
let state = AppState {};
let app = routing::routing(axum::extract::State(state)).await;
let addr = SocketAddr::from(take_args().parse::<SocketAddr>().unwrap());
tokio::spawn(streaming::start());

View file

@ -1,17 +1,20 @@
use crate::{AppState, ServerStatus, CoinStatus, streaming};
use axum::{body::Body, extract::State, http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use crate::{streaming, AppState, CoinStatus, ServerStatus};
use axum::{
body::Body, extract::State, http::StatusCode, response::IntoResponse, routing::get, Json,
Router,
};
use rand::prelude::*;
use tokio::fs::File;
use tokio_util::io::ReaderStream;
use tower_http::cors::CorsLayer;
use rand::prelude::*;
pub async fn routing(State(state): State<AppState>) -> Router {
Router::new()
.route("/", get(alive))
.route("/coin", get(flip_coin))
.route("/stream", get(stream))
.layer(CorsLayer::permissive())
.with_state(state.clone())
.route("/", get(alive))
.route("/coin", get(flip_coin))
.route("/stream", get(stream))
.layer(CorsLayer::permissive())
.with_state(state.clone())
}
async fn alive() -> impl IntoResponse {
@ -24,7 +27,7 @@ async fn alive() -> impl IntoResponse {
async fn flip_coin() -> impl IntoResponse {
let mut rng = rand::thread_rng();
let random:f64 = rng.gen();
let random: f64 = rng.gen();
let mut flip_status = CoinStatus::Tail;
if random > 0.5 {
flip_status = CoinStatus::Head;
@ -43,4 +46,4 @@ async fn stream() -> impl IntoResponse {
let file = File::open("audios/audio.mp3").await.unwrap();
let stream = ReaderStream::new(file);
Body::from_stream(stream)
}
}

View file

@ -1,12 +1,14 @@
use std::{mem::MaybeUninit, sync::Arc, time::Duration};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use ringbuf::{Consumer, HeapRb, Producer, SharedRb};
use tokio::{net::{TcpListener, TcpStream}, time::Instant};
use futures_util::SinkExt;
use ringbuf::{Consumer, HeapRb, Producer, SharedRb};
use tokio::{
net::{TcpListener, TcpStream},
time::Instant,
};
use tokio_tungstenite::WebSocketStream;
pub async fn start() {
let socket = TcpListener::bind("192.168.1.2:2424").await.unwrap();
while let Ok((tcp_stream, _)) = socket.accept().await {
@ -17,21 +19,24 @@ pub async fn start() {
let timer = Instant::now();
tokio::spawn(record(producer));
tokio::spawn(stream(timer, ws_stream, consumer));
}
}
pub async fn stream(timer:Instant, mut ws_stream:WebSocketStream<TcpStream>, mut consumer: Consumer<f32, Arc<SharedRb<f32, Vec<MaybeUninit<f32>>>>>) {
pub async fn stream(
timer: Instant,
mut ws_stream: WebSocketStream<TcpStream>,
mut consumer: Consumer<f32, Arc<SharedRb<f32, Vec<MaybeUninit<f32>>>>>,
) {
println!("Waiting");
loop {
tokio::time::sleep(Duration::from_secs(2)).await;
let mut data:Vec<u8> = Vec::new();
let mut data: Vec<u8> = Vec::new();
let now = timer.elapsed().as_secs();
while !consumer.is_empty() && (timer.elapsed().as_secs()+2) > now{
while !consumer.is_empty() && (timer.elapsed().as_secs() + 2) > now {
match consumer.pop() {
Some(single_data) => {
Some(single_data) => {
let ring = HeapRb::<u8>::new(1000000);
let (mut producer, mut consumer) = ring.split();
let single_data_packet = single_data.to_string().as_bytes().to_vec();
@ -46,9 +51,7 @@ pub async fn stream(timer:Instant, mut ws_stream:WebSocketStream<TcpStream>, mut
data.push(consumer.pop().unwrap());
}
}
None => {
}
None => {}
}
}
ws_stream.send(data.into()).await.unwrap();
@ -63,21 +66,21 @@ pub async fn record(mut producer: Producer<f32, Arc<SharedRb<f32, Vec<MaybeUnini
println!("Input Device: {}", input_device.name().unwrap());
let config:cpal::StreamConfig = input_device.default_input_config().unwrap().into();
let config: cpal::StreamConfig = input_device.default_input_config().unwrap().into();
let input_data_fn = move |data: &[f32], _:&cpal::InputCallbackInfo| {
let input_data_fn = move |data: &[f32], _: &cpal::InputCallbackInfo| {
for &sample in data {
match producer.push(sample) {
Ok(_) => {},
Err(_) => {},
Ok(_) => {}
Err(_) => {}
}
println!("{}", sample);
}
};
let input_stream = input_device.build_input_stream(&config, input_data_fn, err_fn, None).unwrap();
let input_stream = input_device
.build_input_stream(&config, input_data_fn, err_fn, None)
.unwrap();
println!("STREAMIN");
input_stream.play().unwrap();

View file

@ -0,0 +1 @@