Play Audio iOS Objective-C

后端 未结 7 1278
南旧
南旧 2020-11-30 00:25

I\'m trying to get an audio file playing in my iOS app. This is my current code

NSString *soundFilePath = [NSString stringWithFormat:@\"%@/test.m4a\", [[NSBu         


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 00:41

    Updated for Swift 4 Playing from main bundle - iOS 11 only

    import AVFoundation
    
    var player: AVAudioPlayer?
    

    The following code loads the sound file and plays it, returning an error if necessary.

    guard let url = Bundle.main.url(forResource: "test", withExtension: "m4a") else { return }
    
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
    
        guard let player = player else { return }
    
        player.play()
    
        } catch let error {
            // Prints a readable error
            print(error.localizedDescription)
        }
    

提交回复
热议问题