在iOS 8设备上,AudioServicesPlaySystemSound不能播放任何声音

6

我已经将AVFoundationAudioToolbox框架添加到我的项目中。在我想要播放系统声音的类中,我需要#include <AudioToolbox/AudioToolbox.h>并调用AudioServicesPlaySystemSound(1007);方法。我正在测试一个运行iOS 8的设备,声音是开启的,音量足够高,但当我运行应用程序并调用AudioServicesPlaySystemSound(1007);时,我听不到任何系统声音... 我可能漏掉了什么吗?


2
你检查了静音开关吗? - Jason Nam
@JasonNam 是的,声音已经开启了... - AppsDev
其他音频听起来还好吗? - Jason Nam
@JasonNam 铃声和音乐播放良好... - AppsDev
6个回答

9

在iOS10中,像这样播放音频是不起作用的:

SystemSoundID audioID;

AudioServicesCreateSystemSoundID((__bridge CFURLRef)pathURL, &mySSID);
AudioServicesPlaySystemSound(audioID);

请使用以下内容替代:
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pathURL, &audioID);

AudioServicesPlaySystemSoundWithCompletion(audioID, ^{
    AudioServicesDisposeSystemSoundID(audioID);
});

5
根据文档:
此函数(AudioServicesPlaySystemSound())将在未来的版本中被弃用。请使用AudioServicesPlaySystemSoundWithCompletion代替。
使用以下代码片段播放声音:
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:filename withExtension:nil]; //filename can include extension e.g. @"bang.wav"
if (fileURL)
{
    SystemSoundID theSoundID;
    OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)fileURL, &theSoundID);
    if (error == kAudioServicesNoError)
    { 
        AudioServicesPlaySystemSoundWithCompletion(theSoundID, ^{
            AudioServicesDisposeSystemSoundID(theSoundID);
        });
    }
}

此外,完成块确保声音播放完成后再处理它。
如果这并没有解决问题,也许你的问题不是代码相关的,而是设置相关的(设备静音/模拟器声音被MAC系统偏好设置静音,请确保“播放用户界面声效”已选中)。

你能提供文档链接吗?我找不到你引用的内容。 - Suragch
3
这段话来自SDK头文件。如果尝试使用已弃用的方法,XCode将会显示警告消息。 - Ameer Sheikh

2

这将播放系统声音。

但请记住,系统声音不会播放较长时间的声音。

NSString *pewPewPath  = [[NSBundle mainBundle] pathForResource:@"engine" ofType:@"mp3"];
NSURL *pewPewURL = [NSURL fileURLWithPath:pewPewPath];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pewPewURL, &_engineSound);
AudioServicesPlaySystemSound(_engineSound);

1
你能给一些建议吗,如何播放更长时间的声音或重复的音调?我必须一直播放重复的声音,直到电话被接起来。 - Aditya

1

这是在Swift 5.8和Xcode 14中的操作方法:

let soundID: SystemSoundID = 1104 // kSystemSoundID_Tock
AudioServicesPlaySystemSoundWithCompletion(soundID) {
  AudioServicesDisposeSystemSoundID(soundID)
}

⚠️ 请确保设备不处于静音模式!

1
我刚在运行iOS 8的iPad和iPhone上测试了这段代码,它在真实设备上运行正常。 但不知何故,它在iOS 8模拟器上无论是哪种设备都不能工作,尽管它能够在iOS 7和7.1模拟器上运行。 此外,以下代码在所有真实设备上都正常工作。
NSString *pewPewPath  = [[NSBundle mainBundle] pathForResource:@"engine" ofType:@"mp3"];
NSURL *pewPewURL = [NSURL fileURLWithPath:pewPewPath];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pewPewURL, &_engineSound);
AudioServicesPlaySystemSound(_engineSound);

0

适用于 Swift 3.x 和 Xcode 8:

var theSoundID : SystemSoundID = 0
let bundleURL = Bundle.main.bundleURL
let url = bundleURL.appendingPathComponent("Invitation.aiff")

let urlRef = url as CFURL

let err = AudioServicesCreateSystemSoundID(urlRef, &theSoundID)
if err == kAudioServicesNoError{
    AudioServicesPlaySystemSoundWithCompletion(theSoundID, {
        AudioServicesDisposeSystemSoundID(theSoundID)
    })
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接