使用 AVAudioPlayer 在 Swift 中播放远程 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()
    }
}


若文章对您有帮助,帮忙点个赞!

0
-5
发布时间 2021-08-11 14:38:12
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)