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()
}
}
}
Publicado el día 2 de enero de 2024CATEGORÍAS
Swift, Xcode