且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

只需按一下按钮,如何在swift 2中播放m4a文件?

更新时间:2023-08-27 21:54:58

这里有一些代码可以帮助您:

Here is some code to get you going:

Swift 3

import UIKit
import AVFoundation

class ViewController: UIViewController
{
    let player = AVQueuePlayer()

    @IBAction func original(sender: AnyObject) {
        if let url = Bundle.main.url(forResource: "sample_song", withExtension: "m4a") {
            player.removeAllItems()
            player.insert(AVPlayerItem(url: url), after: nil)
            player.play()
        }
    }
}

Swift 2

import UIKit
import AVFoundation

class ViewController: UIViewController
{
    let player = AVQueuePlayer()

    @IBAction func original(sender: AnyObject) {
        if let url = NSBundle.mainBundle().URLForResource("SomeAudioFile", withExtension: "m4a") {
            player.removeAllItems()
            player.insertItem(AVPlayerItem(URL: url), afterItem: nil)
            player.play()
        }
    }
}

您没有解释如果多次按下按钮会发生什么,所以我假设你想要停止正在播放的当前项目并开始一个新项目。

You did not explain what should happen if the button is hit multiple times, so I assumed that you would want to stop the current item being played and start a new one.