ios - 使用 AVAudioPlayer 在 Swift 中播放远程 mp3 文件

标签 ios swift

我是 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 文件?

最佳答案

试试这段代码:

您需要将 AVKitAVFoundation 添加到您的 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/

相关文章:

iphone - 在 UIScrollView 中动态添加的 subview 未出现

ios - 将行间距添加到 textView 不起作用

ios - swift如何去除inputView下的灰色层

ios - 如何以编程方式将图像设置为在每个设备上具有相同的相对大小和位置?

ios - 为什么 MapKit 框架必须链接到每个文件而 CoreData 框架不能?

ios - 如何修复错误 : init(boundsSize:requestHandler:)’ is only available on iOS 10. 0

iphone - 具有动态对象数的自定义 TableView 单元格创建

ios - 无法在 UICollectionView 单元格和单元格 subview 之间添加约束

ios - 如何在 SceneDelegate 中有一个 flutter 方法处理程序?

ios - 如何在 sprite kit swift 中以编程方式在横向中添加 iAd 横幅