You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:无法修复playAudio函数,AVAudioPlayer参数标签不匹配报错

Fixing AVAudioPlayer Initialization Errors in Swift

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 use do-catch to handle errors
  • Swapped contentsOfURL: for the correct modern parameter label contentsOf:
  • Added a guard statement to safely unwrap audioRecorder?.url (avoids force-unwrapping with ! which can crash)
  • Added prepareToPlay() and play() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:26:24