AVAudioPlayer 没有播放任何东西

AVAudioPlayer is no playing anything

我有一个 tableViewCell,我想在其中播放通常为 .m4a 的声音。 我在全球范围内声明了我的 AVAudioPlayer 实例,如下所示:

var player = AVAudioPlayer()

然后我下载我的声音,把它放在Documents的一个目录里。但是,当我尝试从目录播放我的声音文件时,我得到这个错误:

Open failed
The operation couldn’t be completed. (OSStatus error 2003334207.)

这是我的代码我不知道你有什么问题。我在模拟器中找到了可以用 QuickTimePlayer 播放的文件。

func downloadSound(_ message: ChatVoiceMessageStructure) {
    guard let url = service?.networkManager.CDNURL else { return }
    let doanloadURL = URL(string: url.appending(message.name!))
    let docUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let desURL = docUrl.appendingPathComponent("tmpsong.m4a")
    var downloadTask:URLSessionDownloadTask
    let request = URLRequest(url: doanloadURL!)
    downloadTask = URLSession.shared.downloadTask(with: request, completionHandler: { [weak self](URLData, response, error) -> Void in
        do{
            let isFileFound:Bool? = FileManager.default.fileExists(atPath: desURL.path)
            if isFileFound == true{
                print(desURL) //delete tmpsong.m4a & copy
            } else {
                try FileManager.default.copyItem(at: URLData!, to: desURL)
            }
            let sPlayer = try AVAudioPlayer(contentsOf: desURL)
            self?.player = sPlayer
            self?.player.prepareToPlay()
            self?.player.play()

        } catch let err {
            print(err.localizedDescription)
        }

    })
    downloadTask.resume()

}

请在真实设备上运行并在URLSession块中添加DispatchQueue.main.async

我在这里尝试了您的代码,稍作改动后它在真实设备上运行...

var audioPlayer:AVAudioPlayer!
    func downloadSound() {
        let doanloadURL = URL(string: "https://github.com/robovm/apple-ios-samples/raw/master/avTouch/sample.m4a")!
        let docUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let desURL = docUrl.appendingPathComponent("sample.m4a")
        var downloadTask:URLSessionDownloadTask
        let request = URLRequest(url: doanloadURL)
        downloadTask = URLSession.shared.downloadTask(with: request, completionHandler: { (URLData, response, error) -> Void in
            DispatchQueue.main.async {
                do{
                    let isFileFound:Bool? = FileManager.default.fileExists(atPath: desURL.path)
                    if isFileFound == true{
                        print(desURL) //delete tmpsong.m4a & copy
                    } else {
                        try FileManager.default.copyItem(at: URLData!, to: desURL)
                    }
                     let sPlayer = try AVAudioPlayer(contentsOf: desURL)
                    try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
                    try AVAudioSession.sharedInstance().setActive(true)
                    self.audioPlayer = sPlayer
                    self.audioPlayer.prepareToPlay()
                    self.audioPlayer.play()
                  } catch let err {
                    print(err.localizedDescription)
                }
            }
         })
        downloadTask.resume()
     }

多亏了MAhipal,我终于解决了这个问题。问题是 AVAudioPlayer 不能播放某种音频格式。比如当音频扩展名是 MPEG4 但音频编码不是 AAC 时。所以要注意 AVAudioPlayer 支持的格式。您可以在 CoreAudio Class、AudioFormatID 的子 类 中找到这些内容。这花了我几个星期的时间来解决希望它可以节省一些时间。 如果你想玩其他类型你可以使用AVPlayer

这些是供将来参考的类型:

public var kAudioFormatLinearPCM: AudioFormatID { get }
public var kAudioFormatAC3: AudioFormatID { get }
public var kAudioFormat60958AC3: AudioFormatID { get }
public var kAudioFormatAppleIMA4: AudioFormatID { get }
public var kAudioFormatMPEG4AAC: AudioFormatID { get }
public var kAudioFormatMPEG4CELP: AudioFormatID { get }
public var kAudioFormatMPEG4HVXC: AudioFormatID { get }
public var kAudioFormatMPEG4TwinVQ: AudioFormatID { get }
public var kAudioFormatMACE3: AudioFormatID { get }
public var kAudioFormatMACE6: AudioFormatID { get }
public var kAudioFormatULaw: AudioFormatID { get }
public var kAudioFormatALaw: AudioFormatID { get }
public var kAudioFormatQDesign: AudioFormatID { get }
public var kAudioFormatQDesign2: AudioFormatID { get }
public var kAudioFormatQUALCOMM: AudioFormatID { get }
public var kAudioFormatMPEGLayer1: AudioFormatID { get }
public var kAudioFormatMPEGLayer2: AudioFormatID { get }
public var kAudioFormatMPEGLayer3: AudioFormatID { get }
public var kAudioFormatTimeCode: AudioFormatID { get }
public var kAudioFormatMIDIStream: AudioFormatID { get }
public var kAudioFormatParameterValueStream: AudioFormatID { get }
public var kAudioFormatAppleLossless: AudioFormatID { get }
public var kAudioFormatMPEG4AAC_HE: AudioFormatID { get }
public var kAudioFormatMPEG4AAC_LD: AudioFormatID { get }
public var kAudioFormatMPEG4AAC_ELD: AudioFormatID { get }
public var kAudioFormatMPEG4AAC_ELD_SBR: AudioFormatID { get }
public var kAudioFormatMPEG4AAC_ELD_V2: AudioFormatID { get }
public var kAudioFormatMPEG4AAC_HE_V2: AudioFormatID { get }
public var kAudioFormatMPEG4AAC_Spatial: AudioFormatID { get }
public var kAudioFormatAMR: AudioFormatID { get }
public var kAudioFormatAMR_WB: AudioFormatID { get }
public var kAudioFormatAudible: AudioFormatID { get }
public var kAudioFormatiLBC: AudioFormatID { get }
public var kAudioFormatDVIIntelIMA: AudioFormatID { get }
public var kAudioFormatMicrosoftGSM: AudioFormatID { get }
public var kAudioFormatAES3: AudioFormatID { get }
public var kAudioFormatEnhancedAC3: AudioFormatID { get }
public var kAudioFormatFLAC: AudioFormatID { get }
public var kAudioFormatOpus: AudioFormatID { get }