Pet*_*lie 2 audio macos avaudiosession swift
我喜欢在我的应用中播放声音.我发现了很多例子,也可以在Swift 3上编译和运行它们.但是它们总是用于iOS.当在我的应用程序中使用此代码时,AVAudioSession保持未定义.我需要做什么?OSX有什么不同之处吗?
import AVFoundation
...
var audioPlayer = AVAudioPlayer()
func PlaySound( ) {
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "Sound", ofType: "mp3")!)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch _ {
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
}
do {
audioPlayer = try AVAudioPlayer(contentsOf: alertSound)
} catch _{
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
Run Code Online (Sandbox Code Playgroud)
Swift 3/4/4.2/5 - 最简单的解决方案:
NSSound(named: "customSound")?.play()
Run Code Online (Sandbox Code Playgroud)
我已经将以下函数与Swift 3和Cocoa项目结合使用.
import AVFoundation
func playSound(file:String, ext:String) -> Void {
let url = Bundle.main.url(forResource: file, withExtension: ext)!
do {
let player = try AVAudioPlayer(contentsOf: url)
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Run Code Online (Sandbox Code Playgroud)
//用法//
playSound(file: "sound", ext: "caf") // where the file name is sound.caf.
Run Code Online (Sandbox Code Playgroud)
在Xcode项目中选择音频文件时,请确保已启用目标成员资格复选框.
| 归档时间: |
|
| 查看次数: |
2824 次 |
| 最近记录: |