AVPlayer& AVAudioPlayer无法播放来自网址

时间:2017-09-12 11:47:24

标签: ios swift3 avfoundation avplayer avaudioplayer

我试图从网址播放音频。我尝试了AVPlayer和AVAudioPlayer,但没有一个工作。

以下是我要播放的URL

这是我正在使用的代码。

 // AVPlayer Code
 self.avPlayerItem = AVPlayerItem.init(url: urlOfAudio)
 self.avPlayer = AVPlayer.init(playerItem: avPlayerItem)
 self.avPlayer.volume = 1.0
 self.avPlayer.play()

 // AVAudioPlayer
 if let url = URL.init(string: escapeCharactorString){
      do {
           self.playerReference = try AVAudioPlayer.init(contentsOf: url)
           guard let player = playerReference else { 
               return
           }                    
           player.volume = 1.0
           player.prepareToPlay()
           player.numberOfLoops = -1                    
           player.play() 
      } catch let error {

      }
  }

他们都不适合我。 请让我知道我在哪里出错。

1 个答案:

答案 0 :(得分:4)

您的代码没有任何问题,它是完美的,但问题与存储音频文件的服务器设置有关。这是您成功播放其他mp3文件的工作代码,

var avPlayer:AVPlayer?
var avPlayerItem:AVPlayerItem?

override func viewDidLoad() {
    super.viewDidLoad()

//        let urlstring = "http://www.noiseaddicts.com/samples_1w72b820/2514.mp3"
        let urlstring = "https://s3.amazonaws.com/kargopolov/kukushka.mp3"
        let url = NSURL(string: urlstring)
        print("playing \(String(describing: url))")

        avPlayerItem = AVPlayerItem.init(url: url! as URL)
        avPlayer = AVPlayer.init(playerItem: avPlayerItem)
        avPlayer?.volume = 1.0
        avPlayer?.play()

    }

所以请尝试使用不同主机的mp3文件来解决您的问题