【问题标题】:How do I play an m4a file in swift 2 upon the touch of a button?如何在 swift 2 中通过按一下按钮播放 m4a 文件?
【发布时间】:2015-10-11 18:26:45
【问题描述】:

当我触摸一个按钮时如何播放音频文件,我在网上找不到任何东西,因为它都是 swift 1。

我想要original 函数中的音频代码。

import UIKit
import AVFoundation

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

【问题讨论】:

    标签: ios swift audio swift2


    【解决方案1】:

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

    斯威夫特 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()
            }
        }
    }
    

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

    【讨论】:

    • 如果我们添加“mp3”扩展名,它适用于 .mp3 文件。用 Swift 5 播放 m4a 文件的奇怪事情......有什么建议吗?)
    【解决方案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.")
    }
    

    【讨论】:

      【解决方案3】:

      Swift 5 更新:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-06
        • 2014-11-02
        • 1970-01-01
        • 1970-01-01
        • 2020-09-09
        • 1970-01-01
        • 1970-01-01
        • 2012-05-09
        相关资源
        最近更新 更多