gpt4 book ai didi

ios - AVAudioPlayer 不播放 mp3 文件

转载 作者:行者123 更新时间:2023-11-28 13:11:42 25 4
gpt4 key购买 nike

我已经在我的模拟器和我的手机上运行了这个应用程序,并且有多个 mp3 文件,但是我无法从应用程序输出声音。我已将 mp3 文件包含在支持的文件中。老实说,我不知道下一步该怎么做。我没有收到任何错误,但是没有音频。

@IBAction func play (sender: AnyObject){

func sharedInstance() {
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)

var audioPlayer = AVAudioPlayer()
var song = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("pingpong", ofType: "mp3")!)
println(song)



var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: song, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
sharedInstance()

}

最佳答案

只需让您的类的 var audioPlayer = AVAudioPlayer() 全局化,如下面的代码所示:

并且我已经修改了您的代码以使其安全:

import UIKit
import AVFoundation

class ViewController: UIViewController {

var audioPlayer = AVAudioPlayer()

@IBAction func play (sender: AnyObject){

var categoryError: NSError?
if AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &categoryError) {
println("AVAudioSession Category Playback OK")
var activateError: NSError?
if AVAudioSession.sharedInstance().setActive(true, error: &activateError) {
println("AVAudioSession is Active")
var song = NSBundle.mainBundle().URLForResource("we_cant_Stop", withExtension: "mp3")!
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: song, error: &error)
audioPlayer.play()

} else if let activateError = activateError {
println(activateError.description)
}
} else if let categoryError = categoryError {
println(categoryError.description)
}
}
}

这工作正常。

关于ios - AVAudioPlayer 不播放 mp3 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31042459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com