Swift 中的 AudioToolBox - 声音在模拟器中有效,但在我的 iPad 上无效

Posted

技术标签:

【中文标题】Swift 中的 AudioToolBox - 声音在模拟器中有效,但在我的 iPad 上无效【英文标题】:AudioToolBox in Swift - Sound works in Simulator but not on my IPad 【发布时间】:2016-03-13 03:27:38 【问题描述】:

我正在创建一个音乐应用程序,其中将在节奏循环的不同点播放不同的铃声。到目前为止,我的代码在模拟器中运行良好,但我的设备上没有任何声音。我从其他应用程序中获得声音。我的代码有问题吗?谢谢你的帮助!

import UIKit
import AudioToolbox

func playChime1() 
    var chime1URL: NSURL?
    var chime1ID:SystemSoundID = 0
    let filePath = NSBundle.mainBundle().pathForResource("Chime", ofType: "mp3")
    chime1URL = NSURL(fileURLWithPath: filePath!)
    AudioservicesCreateSystemSoundID(chime1URL!, &chime1ID)
    AudioServicesPlaySystemSound(chime1ID)

func playChime2() 
    var chime2URL: NSURL?
    var chime2ID:SystemSoundID = 0
    let filePath = NSBundle.mainBundle().pathForResource("Chime2", ofType: "mp3")
    chime2URL = NSURL(fileURLWithPath: filePath!)
    AudioServicesCreateSystemSoundID(chime2URL!, &chime2ID)
    AudioServicesPlaySystemSound(chime2ID)

func playChime3() 
    var chime3URL: NSURL?
    var chime3ID:SystemSoundID = 0
    let filePath = NSBundle.mainBundle().pathForResource("Chime3", ofType: "mp3")
    chime3URL = NSURL(fileURLWithPath: filePath!)
    AudioServicesCreateSystemSoundID(chime3URL!, &chime3ID)
    AudioServicesPlaySystemSound(chime3ID)

【问题讨论】:

【参考方案1】:

我遇到了同样的问题,并意识到我的 iPhone 处于静音模式,将其关闭静音播放声音。

不幸的是,AudioToolbox 声音响应的是设备的“Ringer”音量,而不是通过 AVFoundation 的音频使用的“Volume”设置。

这是有道理的,因为 AudioToolbox 应该用于系统声音。

【讨论】:

【参考方案2】:

来自相关问题:AudioServicesPlaySystemSound not working on iPad device

您无法在 iDevice 上播放 MP3,需要使用不同的框架。

【讨论】:

设备没有静音,音量一直调高,但还是没有声音。 调用 AudioServicesCreateSystemSoundID 返回一个 OSStatus 代码 - 你检查了吗? 我没有...我该如何检查呢?另外,为什么声音在模拟器上可以工作,但在设备上不行? let errorCode = AudioServicesCreateSystemSoundID(chime3URL, &chime3ID); print(errorCode) 它返回一个“0”...我相信这意味着没有错误,有什么建议可能是错误的吗?感谢您的帮助。【参考方案3】:

我的问题是为 AudioQueue 分配的缓冲区数量,我分配了 3 个,它在 MacOS 上工作,但是对于 iOS 设备,您至少需要 4 个

【讨论】:

以上是关于Swift 中的 AudioToolBox - 声音在模拟器中有效,但在我的 iPad 上无效的主要内容,如果未能解决你的问题,请参考以下文章

iOS调用系统声音和震动

UIAnimations 响应 Swift 中的 MIDI 事件

iOS 8 中的自定义振动 - Swift

iOS6 中的 AudioToolBox 泄漏?

AudioToolbox 库 AVAudioPlayer 中的内存泄漏

iOS开发之音频播放录音