[英]Using AVAudioPlayer to play remote mp3 file in Swift
我是 Swift 的新手,但我想更改我的視圖控制器以在我的 iOS 應用程序中播放遠程 mp3 文件。 我開始使用此代碼在本地播放歌曲,並且它可以工作(之后為播放器提供功能):
import AVFoundation
class Music1ViewController: UIViewController {
//5 -
var songPlayer = AVAudioPlayer()
//15 -
var hasBeenPaused = false
//6 -
func prepareSongAndSession() {
do {
//7 - Insert the song from our Bundle into our AVAudioPlayer
songPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "localsong", ofType: "mp3")!))
//8 - Prepare the song to be played
songPlayer.prepareToPlay()
查看AVAudioPlayer
文檔后, .prepareToPlay()
預加載緩沖區,這讓我覺得我需要做的就是更改初始化程序以定位 URL。
然后我更改初始值設定項:
songPlayer = try AVAudioPlayer(contentsOf: URL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")!)
我在 XCode 中沒有收到任何錯誤,但是當我運行它時,我在控制台中看到Thread 1: EXC_BAD_ACCESS (code=1, address=0x48)
的錯誤Thread 1: EXC_BAD_ACCESS (code=1, address=0x48)
這讓我覺得我正在接近這個錯誤。
有沒有更好的方法來訪問遠程 mp3 文件?
試試這個代碼:
您需要將AVKit
和AVFoundation
添加到您的frameworks
路徑並導入它們:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var player = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func localPress(_ sender: Any) {
let path = Bundle.main.resourcePath!+"/sound.mp3"
print(path)
let url = URL(fileURLWithPath: path)
let playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player.play()
}// i have created a btn for playing a local file, this is it's action
@IBAction func urlPressed(_ sender: Any) {
let playerItem = AVPlayerItem(url: URL(string: "https://yourURL.mp3")!)
player = AVPlayer(playerItem: playerItem)
player.play()
}// i have created another btn for playing a URL file, this is it's action
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
我的方法
func preparePlayer() {
guard let url = URL(string: "https://yourURL.mp3") else {
print("Invalid URL")
return
}
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSessionCategoryPlayback)
let soundData = try Data(contentsOf: url)
audioPlayer = try AVAudioPlayer(data: soundData)
audioPlayer.volume = 1
let minuteString = String(format: "%02d", (Int(audioPlayer.duration) / 60))
let secondString = String(format: "%02d", (Int(audioPlayer.duration) % 60))
print("TOTAL TIMER: \(minuteString):\(secondString)")
} catch {
print(error)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.