Posts

Post not yet marked as solved
0 Replies
543 Views
Hi there, I want to play a stream of audio immediately after the first chunk of the audio arrives. The data stream looks like this Audio_data, Delimiter, Json_data. currently I am handling all chunks before the delimiter and adds it in the queue of the AVQueuePlayer. However, when playing this audio during the stream there are many glitches and does not work well. Waiting until all chunks arrived and then play the audio works well. So I assume there is no problem with the audio data, but with the handling of the chunks as they come and play immediately. Happy about any advice you have! I am pretty lost right now. Thank you so much. import SwiftUI import AVFoundation struct AudioStreamView: View { @State private var players: [AVAudioPlayer] = [] @State private var jsonString: String = "" @State private var queuePlayer = AVQueuePlayer() var streamDelegate = AudioStreamDelegate() var body: some View { VStack(spacing: 20) { Button("Fetch Stream") { fetchDataFromServer() } .padding() TextEditor(text: $jsonString) .disabled(true) .border(Color.gray) .padding() .frame(minHeight: 200, maxHeight: .infinity) } } func fetchDataFromServer() { guard let url = URL(string: "https://dev-sonia.riks0trv4c6ns.us-east-1.cs.amazonlightsail.com/voiceMessage") else { return } var request = URLRequest(url: url) request.httpMethod = "POST" // Specify the request type as POST let parameters: [String: Any] = [ "message_uuid": "value1", "user_uuid": "68953DFC-B9EA-4391-9F32-0B36A34ECF56", "session_uuid": "value3", "timestamp": "value4", "voice_message": "Whats up?" ] request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .fragmentsAllowed) request.addValue("application/json", forHTTPHeaderField: "Content-Type") let task = URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) in guard let strongSelf = self else { return } if let error = error { print("Error occurred: \(error)") return } // You might want to handle the server's response more effectively based on the API's design. // For now, I'll make an assumption that the server returns the audio URL in the response JSON. if let data = data { do { if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let audioURLString = jsonResponse["audioURL"] as? String, let audioURL = URL(string: audioURLString) { DispatchQueue.main.async { strongSelf.playAudioFrom(url: audioURL) strongSelf.jsonString = String(data: data, encoding: .utf8) ?? "Invalid JSON" } } else { print("Invalid JSON structure.") } } catch { print("JSON decoding error: \(error)") } } } task.resume() } func playAudioFrom(url: URL) { let playerItem = AVPlayerItem.init(url: url) queuePlayer.replaceCurrentItem(with: playerItem) queuePlayer.play() } }
Posted
by dustin_kl.
Last updated
.