播放mp3 / wav声音会导致异常

时间:2018-05-25 13:32:51

标签: ios swift avfoundation

使用AVAudioPlayer播放音频时,无论是mp3还是wav,我都会在所有iPad和iPhone 4S以及iOS 9上获得例外。这种情况在任何其他设备上都不会发生。

例外情况来自

com.apple.coreaudio.AQClient (18): breakpoint 2.2

libc++abi.dylib`__cxa_throw:

我正在使用用户断点捕获它。 $ arg1不包含任何内容

这就是我初始化AVAudioPlayer的方式

guard let path = Bundle.main.path(forResource: file, ofType: type) else { return nil }
guard let url = URL(string: path) else { return nil }

try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, with: .mixWithOthers)
try? AVAudioSession.sharedInstance().setActive(true)

return try? AVAudioPlayer(contentsOf: url)

我从异步全局调度队列中播放声音,播放声音的方法包含

self.sound?.prepareToPlay()
self.sound?.play()

最初这个文件是一个wav文件,所以我把它转换成了一个mp3文件,没什么用。我也使用了完全不同的声音,这会产生相同的例外情况。

异常本身并不会使模拟器崩溃,尽管Rollbar会报告SIGSEGV错误带有这样的障碍:

libAVFAudio.dylib in 0x27c1c000

使用的音频类:

import AVFoundation
import Foundation

class Audiotools {
    var sound: AVAudioPlayer?

    let dispatchQueue = DispatchQueue(label: "audio")

    static var shared: Audiotools = {
        let manager = Audiotools()
        return manager
    }()

    init() {
        self.sound = configurePlayer(withFile: Files.sound.name, type: Files.sound.extension)
    }

    func configurePlayer(withFile file: String, type: String) -> AVAudioPlayer? {
        guard let path = Bundle.main.path(forResource: file, ofType: type) else { return nil }
        guard let url = URL(string: path) else { return nil }

        try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, with: .mixWithOthers)
        try? AVAudioSession.sharedInstance().setActive(true)

        return try? AVAudioPlayer(contentsOf: url)
    }

    func playSound() {
        self.dispatchQueue.async {
            self.sound?.prepareToPlay()
            self.sound?.play()
        }
    }
}

其他Rollbar报告:

SIGSEGV: Application terminated
libsystem_platform.dylib in _platform_memmove
AudioToolbox in Cached_DataSource::ReadFromHeaderCache(long long, unsigned int, void*, unsigned int*)
AudioToolbox in Cached_DataSource::ReadBytes(unsigned short, long long, unsigned int, void*, unsigned int*)
AudioToolbox in AudioFileObject::ReadBytes(unsigned char, long long, unsigned int*, void*)
AudioToolbox in AudioFileObject::ReadPacketDataVBR(unsigned char, unsigned int*, AudioStreamPacketDescription*, long long, unsigned int*, void*)
AudioToolbox in AudioFileReadPacketData
AVFAudio in AVAudioPlayerCpp::AQOutputCallbackCore(OpaqueAudioQueue*, AudioQueueBuffer*)
AVFAudio in AVAudioPlayerCpp::prepareToPlayQueue()
AVFAudio in AVAudioPlayerCpp::playQueue(AudioTimeStamp const*)
AVFAudio in AVAudioPlayerCpp::play()
AVFAudio in -[AVAudioPlayer play]

还有其他人有过这种问题吗?

2 个答案:

答案 0 :(得分:1)

事实证明,wav和mp3音频文件都已损坏。转换为aiff解决了这个问题。

答案 1 :(得分:0)

请尝试使用AVAudioSessionCategoryPlayback而不是AVAudioSessionCategoryAmbient。

AVAudioSessionCategoryAmbient:将此类别用于背景声音,如下雨,汽车引擎噪音等。
 与其他音乐混合。

AVAudioSessionCategoryPlayback:将此类别用于音乐曲目。