gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:00:00 26 4
gpt4 key购买 nike

我是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com