如何从ios swift的URL播放mp3音频

时间:2023-01-24 11:55:52

I am getting mp3 url as a response of api calling. I want to play that audio, so how can i do that? (ios swift)

我正在获取mp3 url作为api调用的响应。我想播放那个音频,我怎么做呢?(ios斯威夫特)

here is my response

这是我的回答

 {
    content = "En este primer programa se tratar\U00e1n asuntos tan importante como este y aquel sin descuidar un poco de todo lo dem\U00e1s";
    file = "http://radio.spainmedia.es/wp-content/uploads/2015/12/ogilvy.mp3";
    image = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tapas.jpg";
    number = 0001;
    subtitle = Titulareando;
    title = "Tapa 1";
}

here is my code::

这是我的代码:

 @IBAction func btnplayaudio(sender: AnyObject) {
    let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3"
    let url = NSURL(string: urlstring)
    print("the url = \(url!)")

    play(url!)

}

func play(url:NSURL) {
    print("playing \(url)")

    do {
        self.player = try AVAudioPlayer(contentsOfURL: url)
        player.prepareToPlay()
        player.volume = 1.0
        player.play()
    } catch let error as NSError {
        self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }

}

where am i going wrong?

我哪里做错了?

7 个解决方案

#1


12  

I tried the following,

我试着以下,

    let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3"
    let url = NSURL(string: urlstring)
    print("the url = \(url!)")
    downloadFileFromURL(url!)

Add the below methods,

添加下面的方法,

func downloadFileFromURL(url:NSURL){

    var downloadTask:NSURLSessionDownloadTask
    downloadTask = NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { [weak self](URL, response, error) -> Void in
        self?.play(URL)
    })

    downloadTask.resume()

}

And your play method as it is,

你的游戏方式,

func play(url:NSURL) {
    print("playing \(url)")

    do {
        self.player = try AVAudioPlayer(contentsOfURL: url)
        player.prepareToPlay()
        player.volume = 1.0
        player.play()
    } catch let error as NSError {
        //self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }

}

Download the mp3 file and then try to play it, somehow AVAudioPlayer does not download your mp3 file for you. I am able to download the audio file and player plays it.

下载mp3文件,然后试着播放,AVAudioPlayer并没有为你下载mp3文件。我可以下载音频文件并播放它。

Remember to add this in your info.plist since you are loading from a http source and you need the below to be set for iOS 9+

记住在你的信息中添加这个。因为您正在从http源加载,所以需要为ios9 +设置以下内容

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
</plist>

#2


18  

Use AVPlayer instead of AVAudioPlayer to play remote content. As per documentation AVAudioPlayer needs mp3 file to play Audio. AVAudioPlayer not provide support for streaming.

使用AVPlayer而不是AVAudioPlayer来播放远程内容。根据文档,AVAudioPlayer需要mp3文件播放音频。AVAudioPlayer不支持流媒体。

Try this code , its working fine for me

试试这个代码,它对我来说没问题

func play(url:NSURL) {
    print("playing \(url)")

    do {

        let playerItem = AVPlayerItem(URL: url)

        self.player = try AVPlayer(playerItem:playerItem)
        player!.volume = 1.0
        player!.play()
    } catch let error as NSError {
        self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }
}

Please keep in mind to set App Transport Security(ATS) in info.plist file.

请记住在信息中设置App传输安全(ATS)。plist文件。

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

#3


6  

Since AVPlayer is very limited (for example you cannot change url there without regenerate whole AVPlayer I think you should use AVQueuePlayer:

由于AVPlayer非常有限(例如,如果不重新生成整个AVPlayer,就不能更改url),我认为您应该使用AVQueuePlayer:

From the docs:

从文档:

AVQueuePlayer is a subclass of AVPlayer used to play a number of items in sequence. Using this class you can create and manage a queue of player items comprised of local or progressively downloaded file-based media, such as QuickTime movies or MP3 audio files, as well as media served using HTTP Live Streaming.

AVQueuePlayer是AVPlayer的一个子类,用于按顺序播放多个条目。使用这个类,您可以创建和管理由本地或逐步下载的基于文件的媒体(如QuickTime电影或MP3音频文件)组成的播放器项队列,以及使用HTTP实时流媒体服务的媒体。

So in Swift 3 it will work like this:

所以在《Swift 3》中,它的工作原理是这样的:

lazy var playerQueue : AVQueuePlayer = {
    return AVQueuePlayer()
}()

...

func playTrackOrPlaylist{
    if let url = track.streamURL() { //this is an URL fetch from somewhere. In this if you make sure that URL is valid
        let playerItem = AVPlayerItem.init(url: url)
        self.playerQueue.insert(playerItem, after: nil)
        self.playerQueue.play()
    }
}

#4


1  

Swift 4

斯威夫特4

func playSound(soundUrl: String) {
    let sound = URL(fileURLWithPath: soundUrl)
    do {
        let audioPlayer = try AVAudioPlayer(contentsOf: sound)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }catch let error {
        print("Error: \(error.localizedDescription)")
    }
}

#5


1  

SWIFT 4

斯威夫特4

1 - import AVFoundation

1 -进口AVFoundation

2 - declare player

2 -宣布球员

var player : AVPlayer?

3 - in ViewDidLoad call function and pass the streaming url like String

3 -在ViewDidLoad调用函数,并传递流url如字符串

loadRadio(radioURL: (radioStation?.streamURL)!)

4 - function to play

4 -功能发挥

func loadRadio(radioURL: String) {

        guard let url = URL.init(string: radioURL) else { return }
        let playerItem = AVPlayerItem.init(url: url)
        player = AVPlayer.init(playerItem: playerItem)
        player?.play()
        startNowPlayingAnimation(true)
        played = true
    }

For me is the best and simply way to streaming audio in swift.

对我来说,这是用swift传输音频的最好、最简单的方式。

#6


0  

After some research, and some disappointment since none of the answers solved my problem, I've come to a solution and here's the final result. The accepted answer is half right, you still need to create an AVPlayerLayer

经过一些研究,一些失望,因为没有一个答案解决了我的问题,我找到了一个解决方案,这是最终的结果。接受的答案是对的一半,您仍然需要创建一个AVPlayerLayer

let url = URL(string: "https://www.myinstants.com/media/sounds/cade-o-respeito.mp3" ?? "")
playerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)

let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
self.contentView.layoutSublayers(of: playerLayer)

player?.play()

#7


-1  

To play a sound in swift2 is

在swift2中播放一个声音是

func playSound(soundUrl: String)
{
   let sound = NSURL(soundUrl)
  do{
      let audioPlayer = try AVAudioPlayer(contentsOfURL: sound)
      audioPlayer.prepareToPlay()
      audioPlayer.play()
  }catch {
      print("Error..")
  }
}

Let me know if it working.

如果有用的话,请告诉我。

#1


12  

I tried the following,

我试着以下,

    let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3"
    let url = NSURL(string: urlstring)
    print("the url = \(url!)")
    downloadFileFromURL(url!)

Add the below methods,

添加下面的方法,

func downloadFileFromURL(url:NSURL){

    var downloadTask:NSURLSessionDownloadTask
    downloadTask = NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { [weak self](URL, response, error) -> Void in
        self?.play(URL)
    })

    downloadTask.resume()

}

And your play method as it is,

你的游戏方式,

func play(url:NSURL) {
    print("playing \(url)")

    do {
        self.player = try AVAudioPlayer(contentsOfURL: url)
        player.prepareToPlay()
        player.volume = 1.0
        player.play()
    } catch let error as NSError {
        //self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }

}

Download the mp3 file and then try to play it, somehow AVAudioPlayer does not download your mp3 file for you. I am able to download the audio file and player plays it.

下载mp3文件,然后试着播放,AVAudioPlayer并没有为你下载mp3文件。我可以下载音频文件并播放它。

Remember to add this in your info.plist since you are loading from a http source and you need the below to be set for iOS 9+

记住在你的信息中添加这个。因为您正在从http源加载,所以需要为ios9 +设置以下内容

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
</plist>

#2


18  

Use AVPlayer instead of AVAudioPlayer to play remote content. As per documentation AVAudioPlayer needs mp3 file to play Audio. AVAudioPlayer not provide support for streaming.

使用AVPlayer而不是AVAudioPlayer来播放远程内容。根据文档,AVAudioPlayer需要mp3文件播放音频。AVAudioPlayer不支持流媒体。

Try this code , its working fine for me

试试这个代码,它对我来说没问题

func play(url:NSURL) {
    print("playing \(url)")

    do {

        let playerItem = AVPlayerItem(URL: url)

        self.player = try AVPlayer(playerItem:playerItem)
        player!.volume = 1.0
        player!.play()
    } catch let error as NSError {
        self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }
}

Please keep in mind to set App Transport Security(ATS) in info.plist file.

请记住在信息中设置App传输安全(ATS)。plist文件。

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

#3


6  

Since AVPlayer is very limited (for example you cannot change url there without regenerate whole AVPlayer I think you should use AVQueuePlayer:

由于AVPlayer非常有限(例如,如果不重新生成整个AVPlayer,就不能更改url),我认为您应该使用AVQueuePlayer:

From the docs:

从文档:

AVQueuePlayer is a subclass of AVPlayer used to play a number of items in sequence. Using this class you can create and manage a queue of player items comprised of local or progressively downloaded file-based media, such as QuickTime movies or MP3 audio files, as well as media served using HTTP Live Streaming.

AVQueuePlayer是AVPlayer的一个子类,用于按顺序播放多个条目。使用这个类,您可以创建和管理由本地或逐步下载的基于文件的媒体(如QuickTime电影或MP3音频文件)组成的播放器项队列,以及使用HTTP实时流媒体服务的媒体。

So in Swift 3 it will work like this:

所以在《Swift 3》中,它的工作原理是这样的:

lazy var playerQueue : AVQueuePlayer = {
    return AVQueuePlayer()
}()

...

func playTrackOrPlaylist{
    if let url = track.streamURL() { //this is an URL fetch from somewhere. In this if you make sure that URL is valid
        let playerItem = AVPlayerItem.init(url: url)
        self.playerQueue.insert(playerItem, after: nil)
        self.playerQueue.play()
    }
}

#4


1  

Swift 4

斯威夫特4

func playSound(soundUrl: String) {
    let sound = URL(fileURLWithPath: soundUrl)
    do {
        let audioPlayer = try AVAudioPlayer(contentsOf: sound)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }catch let error {
        print("Error: \(error.localizedDescription)")
    }
}

#5


1  

SWIFT 4

斯威夫特4

1 - import AVFoundation

1 -进口AVFoundation

2 - declare player

2 -宣布球员

var player : AVPlayer?

3 - in ViewDidLoad call function and pass the streaming url like String

3 -在ViewDidLoad调用函数,并传递流url如字符串

loadRadio(radioURL: (radioStation?.streamURL)!)

4 - function to play

4 -功能发挥

func loadRadio(radioURL: String) {

        guard let url = URL.init(string: radioURL) else { return }
        let playerItem = AVPlayerItem.init(url: url)
        player = AVPlayer.init(playerItem: playerItem)
        player?.play()
        startNowPlayingAnimation(true)
        played = true
    }

For me is the best and simply way to streaming audio in swift.

对我来说,这是用swift传输音频的最好、最简单的方式。

#6


0  

After some research, and some disappointment since none of the answers solved my problem, I've come to a solution and here's the final result. The accepted answer is half right, you still need to create an AVPlayerLayer

经过一些研究,一些失望,因为没有一个答案解决了我的问题,我找到了一个解决方案,这是最终的结果。接受的答案是对的一半,您仍然需要创建一个AVPlayerLayer

let url = URL(string: "https://www.myinstants.com/media/sounds/cade-o-respeito.mp3" ?? "")
playerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)

let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
self.contentView.layoutSublayers(of: playerLayer)

player?.play()

#7


-1  

To play a sound in swift2 is

在swift2中播放一个声音是

func playSound(soundUrl: String)
{
   let sound = NSURL(soundUrl)
  do{
      let audioPlayer = try AVAudioPlayer(contentsOfURL: sound)
      audioPlayer.prepareToPlay()
      audioPlayer.play()
  }catch {
      print("Error..")
  }
}

Let me know if it working.

如果有用的话,请告诉我。