簡體   English   中英

AVAudioPlayer無法播放mp3文件

[英]AVAudioPlayer not playing mp3 file

我已經在模擬器,手機以及多個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)
        }
    }
}

一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM