[英]Remote mp3 file taking a lot of time to play in swift ios
我有麻煩了。 我想在我的應用程序中播放遠程mp3文件。 但是mp3文件要花費很多時間(大約5-6分鍾)才能播放。 為什么呢?
任何人都可以建議我該怎么辦?
import UIKit
import AVFoundation
class TestViewController: UIViewController, AVAudioPlayerDelegate {
var player:AVAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func play(sender: AnyObject) {
let url = "http://www.example.com/song.mp3"
let fileURL = NSURL(string: url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()))
let soundData = NSData.dataWithContentsOfURL(fileURL, options: nil, error: nil)
var error: NSError?
self.player = AVAudioPlayer(data: soundData, error: &error)
if player == nil
{
if let e = error
{
println(e.localizedDescription)
}
}
player.volume = 1.0
player.delegate = self
player.prepareToPlay()
player.play()
}
}
提前致謝。
使用AVPlayer而不是AVAudioPlayer來流音頻。 可以這么簡單-
let urlString = "http://www.example.com/song.mp3"
let url = NSURL(string: urlString)
var avPlayer = AVPlayer(URL: url)
avPlayer.play()
您還可以在AVPlayer.status屬性上設置觀察者以管理其更改狀態。 檢出: https : //stackoverflow.com/a/13156942/2484290 (目標c)
當然,AVPlayer文檔在這里: https : //developer.apple.com/LIBRARY/ios/documentation/AVFoundation/Reference/AVPlayer_Class/index.html#//apple_ref/occ/cl/AVPlayer
嘗試使用我的示例來處理緩存和遠程文件。 player.automaticallyWaitsToMinimizeStalling = false //默認情況下為true,因此遠程解決mp3文件中的問題很重要
此功能適用於iOS 10.0+
var player: AVPlayer!
enum AudioType: String {
case remote
case cache
}
@IBAction func remotePressed(_ sender: Any) {
playAudio(type: .remote, fileURL: "http://www.example.com/song.mp3")
}
@IBAction func cachePressed(_ sender: Any) {
if let fileURL = Bundle.main.path(forResource: "jordan", ofType: "mp3") {
playAudio(type: .cache, fileURL: fileURL)
}
}
private func playAudio(type: AudioType, fileURL: String) {
let url = type == .cache ? URL.init(fileURLWithPath: fileURL) : URL.init(string: fileURL)
let playerItem: AVPlayerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)
player.automaticallyWaitsToMinimizeStalling = false//It's important
player.play()
}
可能已經晚了。 是。 @檸檬石灰柚子說了什么。 您應該使用AVPlayer而不是AVAudioPlayer。
您也可以使用MediaPlayer。
import UIKit
import MediaPlayer
@IBAction func playSong(sender: AnyObject) {
print("Song")
self.playAudio("yourAudioURL.mp3")
}
func playAudio(URL:String){
let movieurl:NSURL? = NSURL(string: "\(URL)")
if movieurl != nil {
self.movie = MPMoviePlayerViewController(contentURL: movieurl!)
}
if self.movie != nil {
self.presentViewController(self.movie!, animated: true, completion: nil)
self.movie?.moviePlayer.play()
}
}
這很慢,因為您的程序會在開始播放之前先下載所有歌曲
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.