Background audio playback in UIWebView

2019-06-01 14:52发布

My app allows users to access a service that plays audio books via the web. I am using a UIWebView to handle this.

When the app is exited or the device is put to sleep, the audio stops playing. Since I am just displaying the web view not playing the audio file directly, I cannot use those methods to play the audio in the background.

However, if you access the same link via the Safari app, the audio keeps playing after the phone is put to sleep. How can I achieve the same effect in my app?

1条回答
家丑人穷心不美
2楼-- · 2019-06-01 15:31

First, enable your app for background audio playback in your Info.plist:

<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
</array>

Background Modes

Plist

If you're not already doing so, set up your app for audio playback in your AppDelegate or other class:

import AVFoundation

// ...

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch {
    // Handle setCategory failure
    print(error)
}
查看更多
登录 后发表回答