Swift 4 / Xcode 9.2-音频播放器

时间:2019-05-20 20:03:48

标签: swift avaudiosession

在播放音频时,我在这里做了一个较大的帖子。现在产生最佳版本,但是:

        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)

不起作用,在.playback上给出String成员错误。这是完整的代码:

import Foundation
import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {


@IBAction func triggerSample(_ sender: Any) {
    playSound()
}

var player: AVAudioPlayer?

func playSound() {
    guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)

        /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        /* iOS 10 and earlier require the following line:
         player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */

        guard let player = player else { return }

        player.play()

    } catch let error {
        print(error.localizedDescription)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

更新:该解决方案写在上面注释掉的部分中:对此,针对Xcode 9.2使用以下playSound():

func playSound() {
    guard let url = Bundle.main.url(forResource: "MWSTW_Bowie", withExtension: "mp3") else { return }

    do {
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
        guard let player = player else { return }
        player.play()

    } catch let error {
        print(error.localizedDescription)
    } //end of do/catch

} // end of playSound()

1 个答案:

答案 0 :(得分:0)

那很好。只要确保您的应用程序捆绑包中有一个类型为.mp3

的名为“ soundName”的MP3

enter image description here