简体   繁体   中英

AVPlayer & AVAudioPlayer not playing audio from URL

I have trying to play audio from URL. I tried both AVPlayer and AVAudioPlayer but none of them worked.

Here is the URL which I am trying to play.

Here is the code I am using.

 // 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 {

      }
  }

None of them worked for me. Please let me know where I am going wrong in it.

There is nothing wrong with your code, it is perfect but the issue is something related to server settings that audio file stored. Here is your working code which successfully playing an other mp3 file,

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()

    }

So please try the mp3 file with different host it will solve your problem

The cause is Application Transport Security. You need to add:

<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoadsForMedia</key>
        <true/>
  </dict>

to your application's .plist file to load media from HTTP schemes. HTTPS schemes need no such exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM