How do I play an m4a file in swift 2 upon the touch of a button?

谁说胖子不能爱 提交于 2019-12-22 01:17:28

问题


How do I play an audio file when I touch a button, nothing is working that i can find online because its all swift 1.

I want the audio code in the original function.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    @IBAction func original(sender: AnyObject) {        
    }
}

回答1:


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.




回答2:


if let url = NSBundle.mainBundle().URLForResource("SomeAudioFile", withExtension: "m4a") {
            player.removeAllItems()
            player.insertItem(AVPlayerItem(URL: url), afterItem: nil)
            player.play()
        } else {

print("Go to your Build Phases/Copy Bundle Resources to make sure that your music file IS INDEED there. If not, drag it from the Navigator pane into the Copy Bundle Resources folder.")
}


来源:https://stackoverflow.com/questions/33068559/how-do-i-play-an-m4a-file-in-swift-2-upon-the-touch-of-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!