Contenidos
Cliente en iPhone que graba un audio y lo envía por TCP
Cliente.swift
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
import SwiftUI import AVFoundation struct ContentView: View { let serverAddress = "192.168.1.55" let serverPort = 6001 let audioFilename = "recording.m4a" var body: some View { VStack { Button("Grabar y Enviar") { recordAndSend() } .padding() .foregroundColor(.white) .background(Color.blue) .cornerRadius(8) } .padding() } func recordAndSend() { let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(.playAndRecord, mode: .default) try audioSession.setActive(true, options: .notifyOthersOnDeactivation) audioSession.requestRecordPermission { allowed in guard allowed else { print("No se permite el acceso al micrófono.") return } DispatchQueue.main.async { self.startRecording() } } } catch { print("Error al configurar la sesión de audio: \(error.localizedDescription)") } } func startRecording() { let audioFilenameURL = getDocumentsDirectory().appendingPathComponent(audioFilename) let settings: [String: Any] = [ AVFormatIDKey: kAudioFormatAppleLossless, AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue, AVEncoderBitRateKey: 320000, AVNumberOfChannelsKey: 2, AVSampleRateKey: 44100.0 ] do { let audioRecorder = try AVAudioRecorder(url: audioFilenameURL, settings: settings) audioRecorder.record(forDuration: 5.0) DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { audioRecorder.stop() self.sendAudio(audioFilenameURL) } } catch { print("Error al grabar audio: \(error.localizedDescription)") } } func sendAudio(_ audioFileURL: URL) { do { let audioData = try Data(contentsOf: audioFileURL) var inputStream: InputStream? var outputStream: OutputStream? Stream.getStreamsToHost(withName: serverAddress, port: serverPort, inputStream: &inputStream, outputStream: &outputStream) guard let inputStreamUnwrapped = inputStream, let outputStreamUnwrapped = outputStream else { print("Error al establecer la conexión") return } inputStreamUnwrapped.open() outputStreamUnwrapped.open() let bytesWritten = audioData.withUnsafeBytes { dataBytes in outputStreamUnwrapped.write(dataBytes.bindMemory(to: UInt8.self).baseAddress!, maxLength: audioData.count) } if bytesWritten > 0 { print("Datos de audio enviados con éxito") } else { print("Error al enviar los datos de audio") } inputStreamUnwrapped.close() outputStreamUnwrapped.close() } catch { print("Error al cargar el archivo de audio: \(error.localizedDescription)") } } func getDocumentsDirectory() -> URL { FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] } } @main struct AudioRecordingApp: App { var body: some Scene { WindowGroup { ContentView() } } } |
Configuración del permiso


Servidor creado en IntelliJ IDEA que recibe la grabación del audio
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 |
import java.io.* import java.net.* import java.text.SimpleDateFormat import java.util.Date import java.util.Locale fun main() { val port = 6001 try { val serverSocket = ServerSocket(port) println("Servidor TCP iniciado. Esperando conexiones...") while (true) { val clientSocket = serverSocket.accept() println("Cliente conectado desde: ${clientSocket.inetAddress.hostAddress}") val inputStream = clientSocket.getInputStream() val bufferedInputStream = BufferedInputStream(inputStream) val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) val audioFileName = "audio_$timeStamp.m4a" val fileOutputStream = FileOutputStream(audioFileName) val bufferedOutputStream = BufferedOutputStream(fileOutputStream) val buffer = ByteArray(1024) var bytesRead: Int while (bufferedInputStream.read(buffer).also { bytesRead = it } != -1) { bufferedOutputStream.write(buffer, 0, bytesRead) } bufferedOutputStream.flush() println("Datos de audio recibidos y guardados como '$audioFileName'") bufferedOutputStream.close() fileOutputStream.close() bufferedInputStream.close() inputStream.close() clientSocket.close() } } catch (e: IOException) { e.printStackTrace() } } |
