我收到 mp3 url 作为 API 调用的响应。
我想播放该音频,我该怎么做?
这是我的回复
{
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")
}
}
我哪里出错了?
使用 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 文件中设置应用程序传输安全性(ATS)。
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
我尝试了以下方法:-
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()
}
你的玩法是:-
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")
}
}
下载 mp3 文件,然后尝试播放它,不知何故 AVAudioPlayer 不会为您下载 mp3 文件。我可以下载音频文件并让播放器播放它。
请记住将其添加到您的 info.plist 中,因为您是从 http 源加载的,并且您需要为 iOS 9+
设置以下内容<?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>
创建一个带有进度条和其他东西的完整音频播放器......
swift 5
和 Xcode 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()
}
}
最终结果看起来像这样...
由于
AVPlayer
非常有限(例如,您无法在不重新生成整个url
的情况下更改AVPlayer
)我认为您应该使用AVQueuePlayer
:
来自文档:
AVQueuePlayer 是 AVPlayer 的子类,用于播放多个项目 按顺序。使用此类,您可以创建和管理队列 播放器项目由本地或基于渐进式下载的文件组成 媒体,例如 QuickTime 影片或 MP3 音频文件,以及媒体 使用 HTTP Live Streaming 提供服务。
所以在 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()
}
}
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
}
对我来说,这是快速传输音频的最佳且简单的方法。
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)
}
}
经过一番研究,由于没有一个答案能解决我的问题,我感到有些失望,但我找到了解决方案,这是最终结果。接受的答案只对了一半,您仍然需要创建一个
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()
不要忘记取消静音模式。如果启动静音模式,AvAudioPlayer将不会播放任何声音
斯威夫特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)")
}
}
在 swift2 中播放声音是
func playSound(soundUrl: String)
{
let sound = NSURL(soundUrl)
do{
let audioPlayer = try AVAudioPlayer(contentsOfURL: sound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error..")
}
}
让我知道它是否有效。
您可以创建如下类:
import AVFoundation
final class Player {
static var share = Player()
private var player = AVPlayer()
private init() {}
func play(url: URL) {
player = AVPlayer(url: url)
player.allowsExternalPlayback = true
player.appliesMediaSelectionCriteriaAutomatically = true
player.automaticallyWaitsToMinimizeStalling = true
player.volume = 1
player.play()
}
}
并将其称为:
Player.share.play(url: url)
由于它是单例类,因此很容易管理该播放器的进一步操作。