如何在ios swift中播放来自URL的mp3音频

时间:2016-01-02 06:37:58

标签: ios swift swift2 ios9 avaudioplayer

我收到了mp3 url作为api调用的响应。 我想播放那个音频,那我怎么能这样做呢? (ios swift)

这是我的回复

 {
    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";
}

这是我的代码::

 @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")
    }

}

我哪里错了?

9 个答案:

答案 0 :(得分:23)

使用AVPlayer代替AVAudioPlayer播放远程内容。根据文档,AVAudioPlayer需要mp3文件来播放音频。 AVAudioPlayer不支持streaming

试试这段代码,它对我来说很好

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")
    }
}

请记住在info.plist文件中设置App Transport Security(ATS)。

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

答案 1 :(得分:17)

我尝试了以下内容,

uniqueEmpLoc

添加以下方法,

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

你的游戏方法就是这样,

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

}

下载mp3文件,然后尝试播放它,不知何故,AVAudioPlayer不会为您下载您的mp3文件。我可以下载音频文件,玩家可以播放它。

请记住在info.plist中添加此内容,因为您从 http 来源加载,并且您需要为 iOS 9 +

设置以下内容
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")
    }

}

答案 2 :(得分:7)

由于AVPlayer非常有限(例如,您无法更改url而没有重新生成整个AVPlayer我认为您应该使用AVQueuePlayer

来自docs

  

AVQueuePlayer是AVPlayer的子类,用于播放许多项目   按顺序。使用此类,您可以创建和管理队列   播放器项目包括本地或逐步下载的基于文件的   媒体,如QuickTime电影或MP3音频文件,以及媒体   使用HTTP直播流服务。

所以在 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()
    }
}

答案 3 :(得分:5)

使用进度条和其他内容创建完整的音频播放器... swift 5Xcode 12.1

var player: AVPlayer?
var playerItem:AVPlayerItem?
fileprivate let seekDuration: Float64 = 10


@IBOutlet weak var labelOverallDuration: UILabel!
@IBOutlet weak var labelCurrentTime: UILabel!
@IBOutlet weak var playbackSlider: UISlider!
@IBOutlet weak var ButtonPlay: UIButton!

//call this mehtod to init audio player 
func initAudioPlayer{
    let url = URL(string: "https://argaamplus.s3.amazonaws.com/eb2fa654-bcf9-41de-829c-4d47c5648352.mp3")
    let playerItem:AVPlayerItem = AVPlayerItem(url: url!)
    player = AVPlayer(playerItem: playerItem)
    
    playbackSlider.minimumValue = 0
    
    //To get overAll duration of the audio
    let duration : CMTime = playerItem.asset.duration
    let seconds : Float64 = CMTimeGetSeconds(duration)
    labelOverallDuration.text = self.stringFromTimeInterval(interval: seconds)
    
    //To get the current duration of the audio
    let currentDuration : CMTime = playerItem.currentTime()
    let currentSeconds : Float64 = CMTimeGetSeconds(currentDuration)
    labelCurrentTime.text = self.stringFromTimeInterval(interval: currentSeconds)
    
    playbackSlider.maximumValue = Float(seconds)
    playbackSlider.isContinuous = true
    
    
    
    player!.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: DispatchQueue.main) { (CMTime) -> Void in
        if self.player!.currentItem?.status == .readyToPlay {
            let time : Float64 = CMTimeGetSeconds(self.player!.currentTime());
            self.playbackSlider.value = Float ( time );
            self.labelCurrentTime.text = self.stringFromTimeInterval(interval: time)
        }
        let playbackLikelyToKeepUp = self.player?.currentItem?.isPlaybackLikelyToKeepUp
        if playbackLikelyToKeepUp == false{
            print("IsBuffering")
            self.ButtonPlay.isHidden = true
            //        self.loadingView.isHidden = false
        } else {
            //stop the activity indicator
            print("Buffering completed")
            self.ButtonPlay.isHidden = false
            //        self.loadingView.isHidden = true
        }
    }
   
   //change the progress value
    playbackSlider.addTarget(self, action: #selector(playbackSliderValueChanged(_:)), for: .valueChanged)
    
    //check player has completed playing audio
    NotificationCenter.default.addObserver(self, selector: #selector(self.finishedPlaying(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)}


@objc func playbackSliderValueChanged(_ playbackSlider:UISlider) {
    let seconds : Int64 = Int64(playbackSlider.value)
    let targetTime:CMTime = CMTimeMake(value: seconds, timescale: 1)
    player!.seek(to: targetTime)
    if player!.rate == 0 {
        player?.play()
    }
}

@objc func finishedPlaying( _ myNotification:NSNotification) {
    ButtonPlay.setImage(UIImage(named: "play"), for: UIControl.State.normal)
    //reset player when finish   
    playbackSlider.value = 0
    let targetTime:CMTime = CMTimeMake(value: 0, timescale: 1)
    player!.seek(to: targetTime)
}

@IBAction func playButton(_ sender: Any) {
    print("play Button")
    if player?.rate == 0
    {
        player!.play()
        self.ButtonPlay.isHidden = true
        //        self.loadingView.isHidden = false
        ButtonPlay.setImage(UIImage(systemName: "pause"), for: UIControl.State.normal)
    } else {
        player!.pause()
        ButtonPlay.setImage(UIImage(systemName: "play"), for: UIControl.State.normal)
    }
    
}


func stringFromTimeInterval(interval: TimeInterval) -> String {
    let interval = Int(interval)
    let seconds = interval % 60
    let minutes = (interval / 60) % 60
    let hours = (interval / 3600)
    return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}



@IBAction func seekBackWards(_ sender: Any) {
    if player == nil { return }
    let playerCurrenTime = CMTimeGetSeconds(player!.currentTime())
    var newTime = playerCurrenTime - seekDuration
    if newTime < 0 { newTime = 0 }
    player?.pause()
    let selectedTime: CMTime = CMTimeMake(value: Int64(newTime * 1000 as Float64), timescale: 1000)
    player?.seek(to: selectedTime)
    player?.play()

}


@IBAction func seekForward(_ sender: Any) {
    if player == nil { return }
    if let duration = player!.currentItem?.duration {
       let playerCurrentTime = CMTimeGetSeconds(player!.currentTime())
       let newTime = playerCurrentTime + seekDuration
       if newTime < CMTimeGetSeconds(duration)
       {
          let selectedTime: CMTime = CMTimeMake(value: Int64(newTime * 1000 as 
       Float64), timescale: 1000)
          player!.seek(to: selectedTime)
       }
       player?.pause()
       player?.play()
      }
}

最终结果看起来像这样...

enter image description here

答案 4 :(得分:4)

SWIFT 4

1-import AVFoundation

2-声明玩家

var player : AVPlayer?

3-在ViewDidLoad调用函数中,并像String一样传递流url

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

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
    }

对我来说,是快速流式传输音频的最佳方式。

答案 5 :(得分:3)

经过一些研究,有些失望,因为没有一个答案解决了我的问题,我已经找到了解决方案,这是最终的结果。接受的答案是对的,您仍需要创建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()

答案 6 :(得分:2)

Swift 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)")
    }
}

答案 7 :(得分:0)

var player : AVPlayer?
func playSound()
    {
      guard  let url = URL(string: "https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3")
     else 
        {
          print("error to get the mp3 file")
          return
        }
     do{
         try AVAudioSession.sharedInstance().setCategory(.playback, mode.default)
         try AVAudioSession.sharedInstance().setActive(true)
         player = try AVPlayer(url: url as URL)
         guard let player = player
               else 
                   { 
                     return 
                   }
         player.play()
      } catch let error {
            print(error.localizedDescription)
               }
   }

答案 8 :(得分:-1)

要在swift2中播放声音

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

让我知道它是否有效。