AVPlayer不使用Swift3从Document目录播放音频

时间:2017-05-26 06:51:47

标签: ios swift audio avplayer nsdocumentdirectory

我有一个存储在Document目录中的音频文件。我想用AVPlayer播放它,但它没有播放。我正在使用Swift3。

 var myurl : NSURL!
 var audioPlayer = AVPlayer()

 override func viewWillAppear(_ animated: Bool) {

    super.viewWillAppear(animated)
 // Getting sound from Document directory

    let fileManager = FileManager.default
    let docsurl = try! fileManager.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)

    myurl  = docsurl.appendingPathComponent("/\(songName!)")

   playSound(url:  myurl! as NSURL)

  }
   // Playing Sound

  func playSound(url:NSURL){

        let asset = AVURLAsset(url: url as URL, options: nil)

        let playerItem = AVPlayerItem(asset: asset)

        self.audioPlayer.replaceCurrentItem(with: playerItem)

        let durationInSeconds = CMTimeGetSeconds(asset.duration)

        self.getSeconds = Int(durationInSeconds)

         self.audioPlayer.play()
         } 

我从文档目录中获取url,但它没有播放。不知道为什么? 提前致谢。

1 个答案:

答案 0 :(得分:0)

将此代码放入AppDelegate.swift文件的application:didFinishLaunchingWithOptions:方法中,看看您是否能听到音频:

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
}catch {
    print(error)
}