ios 点击按钮播放声音时出现无法识别的选择器错误

tnkciper  于 2023-05-30  发布在  iOS
关注(0)|答案(2)|浏览(232)

当我试图播放声音时,它给我一个错误。
这就是代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var player: AVAudioPlayer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func buttonC(_sender: UIButton) {
        playSound()
    }
    
    
    
    func playSound() {
        guard let path = Bundle.main.path(forResource: "C", ofType:"wav") else {
            return }
        let url = URL(fileURLWithPath: path)

        do {
            player = try AVAudioPlayer(contentsOf: url)
            player?.play()
            
        } catch let error {
            print(error.localizedDescription)
        }
    }
    
}

这就是错误:

fkaflof6

fkaflof61#

可能您已经重命名了IBAction方法名称,现在它不同了,并且它连接到故事板中以前的名称。断开您的操作方法并适当地重新连接它。
转到你的故事板,选择按钮,然后在connectionInspector (cmd + option + 6)中删除你以前的连接。
然后将按钮正确链接到@IBAction函数。

z4bn682m

z4bn682m2#

这是一个可重用的方法:

import Foundation
import AVFoundation

class SoundManager {
     static let shared = SoundManager()

     var audioPlayer: AVAudioPlayer?

     func playSound(resourse: String, type: SoundType) {
         guard let pathToSound = Bundle.main.path(forResource: resourse, ofType: type.rawValue) else { return }
         let url = URL(fileURLWithPath: pathToSound)
    
         do {
             audioPlayer = try AVAudioPlayer(contentsOf: url)
             audioPlayer?.play()
         } catch {
             //error
         }
     }
}

enum SoundType: String {
    case mp3 = "mp3"
    case wav = "wav"
}

实施:

@IBAction func buttonC(_sender: UIButton) {
    SoundManager.shared.playSound(resourse: "beep", type: .mp3)
}

相关问题