只需按一下按钮,如何在swift 2中播放m4a文件? [英] How do I play an m4a file in swift 2 upon the touch of a button?
本文介绍了只需按一下按钮,如何在swift 2中播放m4a文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我触摸按钮时,如何播放音频文件,我无法在线查找任何内容,因为它全部快速1。
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) {
}
}
推荐答案
这里有一些代码可以帮助您:
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.
这篇关于只需按一下按钮,如何在swift 2中播放m4a文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文