使用AVAudioPlayer在Swift

时间:2017-12-13 06:57:47

标签: ios 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 documentation后,.prepareToPlay()会预先加载缓冲区,这让我觉得我需要做的就是更改初始化程序以定位网址。

然后我更改了初始化程序:

songPlayer = try AVAudioPlayer(contentsOf: URL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")!)

我在XCode中没有收到任何错误,但是当我运行它时,我在Thread 1: EXC_BAD_ACCESS (code=1, address=0x48)的控制台中看到一个错误,这让我觉得我接近这个错误。

有没有更好的方法来访问远程mp3文件?

2 个答案:

答案 0 :(得分:4)

试试这段代码:

您需要添加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()
    }
}

答案 1 :(得分:0)

我的方法

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.prepareToPlay()
            audioPlayer.volume = 0.7
            audioPlayer.delegate = self
            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)
        }
    }