使用AVAudioPlayer无法通过Swift 4播放.m4a

时间:2018-06-29 09:04:28

标签: ios swift avaudioplayer

我使用Alamofire下载iTunes搜索Api的试用音乐。
下载完成后,我想播放音乐。
我尝试修复它,但它没有声音播放。
如何解决这个问题?
谢谢。

import UIKit
import AVFoundation
import Alamofire
import CryptoSwift

class FirstViewController: UIViewController {

    let urlString = "https://audio-ssl.itunes.apple.com/apple-assets-us-std-000001/AudioPreview18/v4/9c/db/54/9cdb54b3-5c52-3063-b1ad-abe42955edb5/mzaf_520282131402737225.plus.aac.p.m4a"

    override func viewDidLoad() {
        super.viewDidLoad()

        let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileName = self.urlString.md5()
            let fileURL = documentsURL.appendingPathComponent("\(fileName).m4a")
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }

        Alamofire.download(urlString, to: destination).response { response in

            if response.error == nil {

                var audioPlayer: AVAudioPlayer!

                do {
                    audioPlayer = try AVAudioPlayer(contentsOf: response.destinationURL!)
                    audioPlayer.prepareToPlay()
                    audioPlayer.play()
                } catch {
                    print("Error:", error.localizedDescription)
                }

            }
        }

    }
}

2 个答案:

答案 0 :(得分:1)

该问题是由于audioPlayer是局部变量这一事实引起的,因此,当您离开完成关闭范围时,它将被释放。因为audioPlayer不会保留在其他任何地方,所以当您离开闭包的作用域时,audioPlayer的引用计数就等于0,这将导致ARC对其重新分配。

此外,您还经常使用强制解包运算符-!-
1)不正确
2)不安全
使用if let构造或guard语句

您需要做的是将播放器存储为FirstViewController类的实例变量。

class FirstViewController: UIViewController {

    let urlString = "https://audio-ssl.itunes.apple.com/apple-assets-us-std-000001/AudioPreview18/v4/9c/db/54/9cdb54b3-5c52-3063-b1ad-abe42955edb5/mzaf_520282131402737225.plus.aac.p.m4a"

    var audioPlayer : AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        // (...)

        Alamofire.download(urlString, to: destination).response { [weak self] (response) in

            if response.error == nil {

                guard let url = response.destinationURL else { return }

                do {
                    self?.audioPlayer = try AVAudioPlayer(contentsOf:  url)
                    self?.audioPlayer?.prepareToPlay()
                    self?.audioPlayer?.play()
                } catch {
                    print("Error:", error.localizedDescription)
                }
            }
        }
    }
}

答案 1 :(得分:0)

只需将audioPlayer移至控制器

class FirstViewController: UIViewController {

    let urlString = "https://audio-ssl.itunes.apple.com/apple-assets-us-std-000001/AudioPreview18/v4/9c/db/54/9cdb54b3-5c52-3063-b1ad-abe42955edb5/mzaf_520282131402737225.plus.aac.p.m4a"
    var audioPlayer: AVAudioPlayer?

   //Downloading code......
}
相关问题