ios - 使用swift在后台播放歌曲的本地通知?

标签 ios swift avfoundation uilocalnotification

这是我的代码:

import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var audioPlayer:AVAudioPlayer?

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    //        let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)

    let playAction = UIMutableUserNotificationAction()
    playAction.identifier = "PLAY"
    playAction.title = "play"
    playAction.activationMode = UIUserNotificationActivationMode.Background
    playAction.authenticationRequired = false
    playAction.destructive = true


    let playCategory = UIMutableUserNotificationCategory()
    playCategory.identifier = "PLAY_CATEGORY"
    playCategory.setActions([playAction],
                               forContext: UIUserNotificationActionContext.Default)

    let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: NSSet(object: playCategory) as? Set<UIUserNotificationCategory>)
    UIApplication.sharedApplication().registerUserNotificationSettings(settings)

    return true
}
 func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if identifier == "PLAY" {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.playSound("play_tune")
       }
 func playSound(soundName: String)
{

    if (audioPlayer != nil && (audioPlayer?.playing)!) {
        return
    }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        print("AVAudioSession Category Playback OK")
        do {
            try AVAudioSession.sharedInstance().setActive(true)
            print("AVAudioSession is Active")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }

    let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "mp3")!)
    do{
        audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
        audioPlayer!.prepareToPlay()
        audioPlayer!.play()
    }catch {
        print("Error getting the audio file")
    }


}

一切正常,但当我在通知中按下播放时,什么也没有发生。我希望当用户收到通知时,如果他/她按下播放按钮,歌曲应该在后台播放。

谢谢。

最佳答案

请在您的 playSound 函数中添加这些代码行

var soundID = SystemSoundID()
var soundFile = Bundle.main.path(forResource: "msg_tone", ofType: "mp3")!
AudioServicesCreateSystemSoundID((URL(fileURLWithPath: soundFile) as! CFURLRef), soundID)
AudioServicesPlaySystemSound(soundID)

在变量 coinSound 之后...

关于ios - 使用swift在后台播放歌曲的本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40506503/

相关文章:

ios - 在单个 View 中捏合放大多个图像(Swift)

android - 将移动应用程序 bundle 到单个下载中

ios - 如何在SwiftUI中更改NavigationView目标?

ios - 将一个 NSString 复制到另一个 Xcode

swift - Realm 迁移 : Migrate an object into a List

ios - 焦点图像的 UIImage 部分

ios - 根据条件更改 CollectionView 中选定单元格的颜色

swift - 预期错误的参数类型 - Swift 4

ios - 如何在 iOS 中将 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange 缓冲区转换为 UIImage

ios - 为什么在 AVCapturePhotoOutput 上调用 .capturePhoto(with :, delegate:) 会导致崩溃