swift2 如何在swift 2中按下按钮后播放m4a文件?

zujrkrfu  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(232)

我如何播放一个音频文件时,我触摸一个按钮,没有什么是工作,我可以在网上找到,因为它的所有swift 1。
我需要original函数中的音频代码。

import UIKit
import AVFoundation

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

jchrr9hc1#

下面是一些代码:

雨燕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()
        }
    }
}

雨燕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()
        }
    }
}

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

hmmo2u0o

hmmo2u0o2#

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.")
}
2nbm6dog

2nbm6dog3#

Swift 5更新:

if let url = Bundle.main.url(forResource: "SomeAudioFile", withExtension: "m4a") {
        player.removeAllItems()
        player.insert(AVPlayerItem(url: url), after: nil)
        player.play()
    }

相关问题