ios AVAudioPlayer 不在 Swift 中播放音频
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24792783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AVAudioPlayer not playing audio in Swift
提问by Kenneth
I have this code in a very simple, single view Swift application in my ViewController
:
我在我的一个非常简单的单视图 Swift 应用程序中有此代码ViewController
:
var audioPlayer = AVAudioPlayer()
@IBAction func playMyFile(sender: AnyObject) {
let fileString = NSBundle.mainBundle().pathForResource("audioFile", ofType: "m4a")
let url = NSURL(fileURLWithPath: fileString)
var error : NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
if (audioPlayer.isEqual(nil)) {
println("There was an error: (er)")
} else {
audioPlayer.play()
NSLog("working")
}
I have added import AVFoundation
and audioPlayer
is a global variable. When I execute the code, it does print "working", so it makes it through without errors but no sound is played. The device is not in silent.
我添加了import AVFoundation
并且audioPlayer
是一个全局变量。当我执行代码时,它会打印“工作”,因此它可以无错误地通过,但没有播放声音。设备未处于静音状态。
回答by matt
There's so much wrong with your code that Socratic method breaks down; it will probably be easiest just to throw it out and show you:
你的代码有很多错误,以至于苏格拉底方法崩溃了;把它扔掉并展示给你看可能是最简单的:
var player : AVAudioPlayer! = nil // will be Optional, must supply initializer
@IBAction func playMyFile(sender: AnyObject?) {
let path = NSBundle.mainBundle().pathForResource("audioFile", ofType:"m4a")
let fileURL = NSURL(fileURLWithPath: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()
}
I have not bothered to do any error checking, but the upside is you'll crash if there's a problem.
我没有费心做任何错误检查,但好处是如果出现问题你会崩溃。
One final point, which may or may not be relevant: not every m4a
file is playable. A highly compressed file, for example, can fail silently (pun intended).
最后一点,可能相关也可能不相关:并非每个m4a
文件都可以播放。例如,高度压缩的文件可能会静默失败(双关语)。
回答by iHolm
Important that AvPlayer is class member and not in the given function, else it goes out of scope... :)
重要的是 AvPlayer 是类成员而不是在给定的函数中,否则它超出范围...... :)
回答by bpolat
Here is a working snippet from my swift project. Replace "audiofile" by your file name.
这是我的 swift 项目中的一个工作片段。用您的文件名替换“audiofile”。
var audioPlayer = AVAudioPlayer()
let audioPath = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("audiofile", ofType: "mp3"))
audioPlayer = AVAudioPlayer(contentsOfURL: audioPath, error: nil)
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
audioPlayer.play()
You can download fully functional Swift Audio Player application source code from here https://github.com/bpolat/Music-Player
您可以从这里下载功能齐全的 Swift 音频播放器应用程序源代码 https://github.com/bpolat/Music-Player
回答by Anonymous
for some reason (probably a bug) Xcode can't play certain music files in the .m4a and the .mp3 format I would recommend changing them all to .wav files to get it to play
出于某种原因(可能是错误)Xcode 无法播放 .m4a 和 .mp3 格式的某些音乐文件我建议将它们全部更改为 .wav 文件以使其播放
//top of your class
var audioPlayer = AVAudioPlayer
//where you want to play your sound
let Sound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "wav")!)
do {
audioPlayer = try AVAudioPlayer(contentsOf: Sound as URL)
audioPlayer.prepareToPlay()
} catch {
print("Problem in getting File")
}
audioPlayer.play()
回答by Aleksey Shevchenko
Based on @matt answer but little bit detailed 'cause original answer did not completely satisfied me.
基于@matt 答案,但有点详细,因为原始答案并没有让我完全满意。
import AVFoundation
class YourController: UIViewController {
private var player : AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
prepareAudioPlayer()
}
@IBAction func playAudio() {
player?.play()
}
}
extension YourController: AVAudioPlayerDelegate {}
private extension YourController {
func prepareAudioPlayer() {
guard let path = Bundle.main.path(forResource: "you-audio", ofType:"mp3") else {
return
}
let fileURL = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: fileURL)
} catch let ex {
print(ex.localizedDescription)
}
player?.prepareToPlay()
player?.delegate = self
}
}
回答by Badr
I had to declare a global player variable
我必须声明一个全局玩家变量
var player: AVAudioPlayer!
and set it in viewDidLoad
并将其设置在 viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
player = AVAudioPlayer()
}
Then I could play the audio file wherever like this:
然后我可以像这样在任何地方播放音频文件:
func playAudioFile(){
do {
if audioFileUrl == nil{
return
}
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: audioFileUrl, fileTypeHint: AVFileType.m4a.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
print("PLAYING::::: \(audioFileUrl)")
}
catch let error {
print(error.localizedDescription)
}
}
}
}
回答by William Kane
var audioPlayer = AVAudioPlayer()
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("KiepRongBuon", ofType: "mp3")!)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
回答by Prashanth Ds
I used the below code in my app and it works. Hope that is helpful.
我在我的应用程序中使用了以下代码并且它有效。希望这是有帮助的。
var audioPlayer: AVAudioPlayer!
if var filePath = NSBundle.mainBundle().pathForResource("audioFile", ofType:"mp3"){
var filePathUrl = NSURL.fileURLWithPath(filePath)
audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
audioPlayer.play()
}else {
println("Path for audio file not found")
}
回答by Iyyappan Ravi
In Swift Coding using Try catch, this issues will solve and play audio for me and my code below,
在使用 Try catch 的 Swift Coding 中,此问题将为我和下面的代码解决并播放音频,
var playerVal = AVAudioPlayer()
@IBAction func btnPlayAction(sender: AnyObject) {
let fileURL: NSURL = NSURL(string: url)!
let soundData = NSData(contentsOfURL: fileURL)
do {
playerVal = try AVAudioPlayer(data: soundData!)
}
catch {
print("Something bad happened. Try catching specific errors to narrow things down",error)
}
playerVal.delegate = self
playerVal.prepareToPlay()
playerVal.play()
}
回答by ronak patel
swift 3.0:
快速 3.0:
import UIKit
import AVFoundation
class ViewController: UIViewController
{
var audioplayer = AVAudioPlayer()
@IBAction func Play(_ sender: Any)
{
audioplayer.play()
}
@IBAction func Pause(_ sender: Any)
{
if audioplayer.isPlaying
{
audioplayer.pause()
}
else
{
}
}
@IBAction func Restart(_ sender: Any)
{
if audioplayer.isPlaying
{
audioplayer.currentTime = 0
audioplayer.play()
}
else
{
audioplayer.play()
}
}
override func viewDidLoad()
{
super.viewDidLoad()
do
{
audioplayer = try AVAudioPlayer(contentsOf:URL.init(fileURLWithPath:Bundle.main.path(forResource:"bahubali", ofType: "mp3")!))
audioplayer.prepareToPlay()
var audioSession = AVAudioSession.sharedInstance()
do
{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}
catch
{
}
}
catch
{
print (error)
}
}
}