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 |
import SwiftUI import AVFoundation class AudioPlayerManager: NSObject, ObservableObject, AVAudioPlayerDelegate { let audioFileName = "recording.wav" var audioFileURL: URL { getDocumentsDirectory().appendingPathComponent(audioFileName) } var audioPlayer: AVAudioPlayer! override init() { super.init() do { audioPlayer = try AVAudioPlayer(contentsOf: audioFileURL) audioPlayer.delegate = self audioPlayer.prepareToPlay() } catch { print("Error al inicializar el reproductor de audio: \(error.localizedDescription)") } } func startRecording() { let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.wav") let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(.playAndRecord, mode: .default, options: []) try audioSession.setActive(true) let settings: [String: Any] = [ AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 44100.0, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] let audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings) audioRecorder.record() DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) { audioRecorder.stop() print("Grabación finalizada") print("Audio file is stored at: \(audioFilename)") } } catch { print("Error al iniciar la grabación: \(error.localizedDescription)") } } func playAudio() { guard FileManager.default.fileExists(atPath: audioFileURL.path) else { print("Archivo de audio no encontrado.") return } audioPlayer.play() } func getDocumentsDirectory() -> URL { FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { if flag { print("La reproducción del audio terminó exitosamente.") } else { print("Hubo un problema al reproducir el audio.") } } } struct ContentView: View { @StateObject var audioPlayerManager = AudioPlayerManager() var body: some View { VStack { Button(action: { audioPlayerManager.startRecording() }) { Text("Iniciar grabación") .padding() .foregroundColor(.white) .background(Color.blue) .cornerRadius(8) } Button(action: { audioPlayerManager.playAudio() }) { Text("Reproducir Audio") .padding() .foregroundColor(.white) .background(Color.blue) .cornerRadius(8) } } } } @main struct YourApp: App { var body: some Scene { WindowGroup { ContentView() } } } |