swift2 AVFoundation -播放wav文件(应用程序包外)Swift 2.1

vwhgwdsa  于 2022-11-06  发布在  Swift
关注(0)|答案(2)|浏览(167)

我只是用Swift做了一点实验(这是第一次)。除了错误检查和适当的应用程序结构之外,我认为这应该可以播放音频:

import Foundation
import AVFoundation

var audioPlayer: AVAudioPlayer!
let file = "/Users/mtwomey/Desktop/test1/test1/a2002011001-e02.wav"

let url = NSURL(fileURLWithPath: file)
print(url)
audioPlayer = try! AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: file), fileTypeHint: "wav")
audioPlayer.play()
print("Done.")

然而,它并没有。当我运行这个应用程序时,它只是继续打印“完成”并退出。如果文件名/文件路径不正确,我会得到一个异常(因此它看起来实际上正在访问文件)。
我试图证明一个概念的控制台应用程序,这将需要访问的波形文件以外的应用程序包。任何提示,我错过了什么?

bbmckpt7

bbmckpt71#

我发现,在执行swift文件时无法播放音频的主要问题是:* 命令行工具在AVAudioPlayer准备好播放之前退出 *(在异步操作完成之前)。
这是我的解决方案(使用DispatchGroup),它可以通过从命令行工具(无Playground)执行我的Swift文件(用Swift 5.x编写)来播放我的mp3文件。

import Foundation
import AVFoundation

var testAudio = AVAudioPlayer()

let path = FileManager.default.currentDirectoryPath + "/example.mp3"

let url = URL(fileURLWithPath: path)

let group = DispatchGroup()
group.enter()

DispatchQueue.main.async {
    do {
        testAudio = try AVAudioPlayer(contentsOf: url)
    } catch let err {
        print("Failed play audio: \(err)")
    }

    group.leave()
}

group.notify(queue: .main) {
    print("play audio")
    testAudio.play()
}

dispatchMain()
xdyibdwo

xdyibdwo2#

试试这个,

import UIKit
import AVFoundation

class ViewController: AVAudioPlayerDelegate{
var audioPlayer: AVAudioPlayer!  // Declaring this outside your function, as class variable is important! otherwise your player won't be able to play the sound.

override func viewDidLoad() {
    super.viewDidLoad()
    self.playSound("/Users/mtwomey/Desktop/test1/test1/a2002011001-e02.wav")
}

func playSound(soundPath: String)
{
    let sound = NSURL(fileURLWithPath: soundPath)
    do{
        audioPlayer = try AVAudioPlayer(contentsOfURL: sound, fileTypeHint: "wav")
        audioPlayer.prepareToPlay()
        audioPlayer.delegate = self
        audioPlayer.play()
    }catch {
        print("Error getting the audio file")
    }
}

或(如果您已经将档案放置在项目中)(请遵循此blog post以了解如何将档案放置在项目中)

import UIKit
import AVFoundation

class ViewController: AVAudioPlayerDelegate{
var audioPlayer: AVAudioPlayer!  // Declaring this outside your function, as class variable is important! otherwise your player won't be able to play the sound.

override func viewDidLoad() {
    super.viewDidLoad()
    self.playSound("sound-name")
}

func playSound(soundName: String)
{
    let sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "wav")!)
    do{
        audioPlayer = try AVAudioPlayer(contentsOfURL: sound, fileTypeHint: "wav")
        audioPlayer.prepareToPlay()
        audioPlayer.delegate = self
        audioPlayer.play()
    }catch {
        print("Error getting the audio file")
    }
}

相关问题