AVAudioPlayer not playing audio in Swift

后端 未结 10 1468
抹茶落季
抹茶落季 2020-12-16 03:10

I have this code in a very simple, single view Swift application in my ViewController:

var audioPlayer = AVAudioPlayer()

@IBAction func playMyF         


        
10条回答
  •  星月不相逢
    2020-12-16 03:26

    swift 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)
                }
    
            }
         }   
    

提交回复
热议问题