ios - AudioServicesPlaySystemSound 奇怪的行为

标签 ios objective-c xcode swift audio

我的 AudioServicesPlaySystemSound 出现这种不稳定的行为。

出于某种原因,在我的(真实设备)iPhone 5/6 上一切都运行良好。但有时在我的(真实设备)iPhone 6+S 上,我听到 - 有时 - 只有 3 或 2 个声音我正在玩的 5 首

我用来创建这种声音的函数:

  if let soundURL = NSBundle.mainBundle().URLForResource(soundName, withExtension: "mp3") {
            var mySound: SystemSoundID = 0
            AudioServicesCreateSystemSoundID(soundURL, &mySound)

            AudioServicesPlaySystemSound(mySound);

        }

最佳答案

你应该在代码中进行一些调试并找出问题的真正原因,以下代码将打印出OSStatus:

let result = AudioServicesCreateSystemSoundID(soundURL, &mySound)
print(result)

当结果不为0时,你需要弄清楚哪里出了问题,最常见的问题是声音文件应该小于30秒,否则将无法通过系统声音服务播放。

另一个问题是您应该在应用程序启动时创建系统声音,然后在需要时播放返回的 mySound,不要每次播放时都调用 AudioServicesCreateSystemSoundID。

import UIKit
import AudioToolbox

class ViewController: UIViewController {
    var mySound: SystemSoundID = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let soundName = "mytest"

        if let soundURL = NSBundle.mainBundle().URLForResource(soundName, withExtension: "mp3") {
            let result = AudioServicesCreateSystemSoundID(soundURL, &mySound)
            print(mySound)
            print(result)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func play (sender: UIButton) {
            AudioServicesPlaySystemSound(mySound);
    }
}

关于ios - AudioServicesPlaySystemSound 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34493063/

相关文章:

objective-c - 将 swift 代码桥接到 obj c 项目中

ios - UIScrollView 子级坐标反转

ios - UITableView 滚动性能

ios - iOS 8 和 iOS 9 中相同代码的不同行为的可能原因

ios - 警告 : Method override for designated initializer

xcode - 出于开发目的,我如何模拟 Apple Watch?

ios - Swift Sqlite 模型绑定(bind)

ios - 用于简单 HTML 的 UIWebView 与 WebKit

Android/iOS OpenCV 扩眼检测

ios - iOS 中纵向和横向 View 的不同布局和约束?