求助:无法修复playAudio函数,AVAudioPlayer参数标签不匹配报错
Hey there! Let's get those AVAudioPlayer errors sorted out—they're classic mix-ups with how AVFoundation's APIs changed in modern Swift versions.
Why You're Seeing Those Errors
Older versions of Swift used AVAudioPlayer(contentsOfURL:error:) with an error pointer, but modern Swift switched to a throwable initializer that uses contentsOf: as the parameter label, and relies on do-catch blocks to handle errors instead of passing an error variable directly. Your attempts to tweak the labels were on the right track, but you needed to adjust the entire error-handling pattern too.
Corrected Code
Here's how to fix your playAudio function properly:
import AVFoundation // Make sure you have these properties declared in your class var audioRecorder: AVAudioRecorder? var audioPlayer: AVAudioPlayer? @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var stopButton: UIButton! @IBAction func playAudio(sender: AnyObject) { if audioRecorder?.isRecording == false { stopButton.isEnabled = true recordButton.isEnabled = false guard let audioURL = audioRecorder?.url else { print("Error: No audio URL found from recorder") return } do { // Use the modern throwable initializer with `contentsOf:` audioPlayer = try AVAudioPlayer(contentsOf: audioURL) // Optional: Prepare the player and start playback audioPlayer?.prepareToPlay() audioPlayer?.play() } catch let playbackError { // Catch and print any errors that occur print("Failed to initialize audio player: \(playbackError.localizedDescription)") } } }
Key Changes Made:
- Removed the old
let error : NSError?line—we now usedo-catchto handle errors - Swapped
contentsOfURL:for the correct modern parameter labelcontentsOf: - Added a
guardstatement to safely unwrapaudioRecorder?.url(avoids force-unwrapping with!which can crash) - Added
prepareToPlay()andplay()to actually start the audio (your original code cut off, but this is a common missing piece) - Added error handling to print out exactly what went wrong if initialization fails
This should resolve both of your overload mismatch errors, and make your code safer with proper optional handling.
内容的提问来源于stack exchange,提问作者Alex Grinberg

