加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ios – 在使用Swift时,我的应用仍然播放声音时,如何允许背景音乐

发布时间:2020-12-15 01:38:55 所属栏目:百科 来源:网络整理
导读:我创建了一个应用程序,我试图允许用户在玩我的游戏时继续听他们的音乐,但是当他们打“播放”,并且发出声音时会停止背景音乐.我正在使用Swift在iOS上开发.这是一段启动游戏声音的代码. func playSpawnedDot() { var alertSound: NSURL = NSURL(fileURLWithPat
我创建了一个应用程序,我试图允许用户在玩我的游戏时继续听他们的音乐,但是当他们打“播放”,并且发出声音时会停止背景音乐.我正在使用Swift在iOS上开发.这是一段启动游戏声音的代码.

func playSpawnedDot() {
    var alertSound: NSURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("spawnDot",ofType: "mp3")!)!
    var error:NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: alertSound,error: &error)
    audioPlayer.prepareToPlay()

    if volumeBool {
        audioPlayer.play()
    }
}

解决方法

您需要设置AVAudioSession类别,具有以下值之一: https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/index.html(AVAudioSession类参考).

默认值设置为AVAudioSessionCategorySoloAmbient.如你所见:

[…] using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable. To allow mixing,use the AVAudioSessionCategoryAmbient category instead.

在播放声音之前,您必须更改该类别.这样做:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient,error: nil)
AVAudioSession.sharedInstance().setActive(true,error: nil)

每次播放声音时都不需要调用这些行.你可能只想做一次.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读