我是 Swift 的新手,但我想更改我的 View Controller 以在我的 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
之后documentation , .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)
的错误,这让我认为我正在接近这个错误。
有没有更好的方法来访问远程 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()
}
}
关于ios - 使用 AVAudioPlayer 在 Swift 中播放远程 mp3 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47787225/