Fixing an AVAudioPlayer Crash

Background

I once ran into a multithreaded crash related to AVAudioPlayer. This article records the investigation and the fix.

The crash stack looked like this:

1
2
3
4
5
6
7
8
9
10
Crashed: com.apple.main-thread
0 libobjc.A.dylib 0x1834fc910 objc_msgSend + 16
1 AVFAudio 0x189c814f4 -[AVAudioPlayer(AVAudioPlayerPriv) finishedPlaying:] + 92
2 Foundation 0x184d7a0ec __NSThreadPerformPerform + 340
3 CoreFoundation 0x1842d7404 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 24
4 CoreFoundation 0x1842d6c2c __CFRunLoopDoSources0 + 276
5 CoreFoundation 0x1842d479c __CFRunLoopRun + 1204
6 CoreFoundation 0x1841f4da8 CFRunLoopRunSpecific + 552
7 GraphicsServices 0x1861d9020 GSEventRunModal + 100
8 UIKit 0x18e211758 UIApplicationMain + 236

After searching around, I found that other developers had also encountered similar issues:

I also tried a few solutions suggested online, but they did not work in this case:

Analysis

From the stack, the crash was likely caused by accessing an invalid address inside finishedPlaying:. The presence of _objc_msgSend also strongly suggested a multithreading issue.

AVAudioPlayer plays audio asynchronously. It starts a separate playback thread rather than running playback directly on the main thread. After playback finishes, it switches back to the main thread and calls AVAudioPlayer’s finishedPlaying: method, which then invokes the delegate callback.

During the switch from the playback thread back to the main thread, AVAudioPlayer itself is retained and will not be released. However, its delegate may already have been released. In that situation, AVAudioPlayer may still attempt to call a method on the delegate, which can lead to a crash.

I also found a similar explanation through Google:

1
2
3
4
The cause of this problem was that the AVAudioPlayer object was trying
to invoke [avAudioPlayer.delegate audioPlayerDidFinishPlaying] but the
avAudioPlayer.delegate ref was no longer valid because it had been
deallocated when releasing the avAudioPlayer in my code

The AVAudioPlayer.h header declares the delegate as weak. At first glance, this makes the crash puzzling, especially because it appears across many iOS versions and device models.

1
2
3
4
5
6
7
8
9
10
// AVAudioPlayer.h
@interface AVAudioPlayer : NSObject {
@private
id _impl;
}

// the delegate will be sent messages from the AVAudioPlayerDelegate protocol
@property(weak, nullable) id<AVAudioPlayerDelegate> delegate;

@end

Debugging

Because finishedPlaying: is not exposed as a public method, I hooked it so that I could inspect the stack.

Fixing an AVAudioPlayer Crash: Debugging (figure 1) Fixing an AVAudioPlayer Crash: Debugging (figure 2)

During debugging, I found that AVAudioPlayer has an internal implementation class named AudioPlayerImpl, and this internal class also has a member variable named _delegate.

I then checked the header for AudioPlayerImpl in more detail: AudioPlayerImpl header

Fixing an AVAudioPlayer Crash: Debugging (figure 3)

After verification, I found that these two delegate fields pointed to the same object:

1
2
3
4
5
 (lldb) po self.delegate
<ThreadViewController: 0x7ff3334025e0>

Printing description of self->_impl->_delegate:
<ThreadViewController: 0x7ff3334025e0>

This made me suspect that the _delegate member inside the internal AudioPlayerImpl object was the real problem. My initial guess was that the crash happened like this:

Assume that the delegate of AVAudioPlayer is A, and the _delegate member variable inside AudioPlayerImpl is B.

In an ideal design, when the external delegate is released, the weak reference A should automatically become nil. At the same time, B should also be set to nil, and the two changes should be kept atomic. But in some cases, A and B may not stay perfectly synchronized. A may have already become nil, while B still points to an invalid address. If B is accessed at that moment, the app crashes.

Fix

Based on that suspicion, I tried a simple fix:

Before executing finishedPlaying, first check whether AVAudioPlayer’s delegate is nil.

  • If it is nil, also set the _delegate member of AudioPlayerImpl to nil.
  • Otherwise, strongly retain AVAudioPlayer’s delegate so that it remains alive while finishedPlaying: is executing.

The defensive hook looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@implementation AVAudioPlayer (Extension)

+ (void)load {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
dm_swizzleSelector([self class], @selector(finishedPlaying:), @selector(dm_finishedPlaying:));
#pragma clang diagnostic pop
}

- (void)dm_finishedPlaying:(id)success {

Ivar ivar = class_getInstanceVariable([self class], "_impl");
id impl = object_getIvar(self, ivar);
NSString *implClassName = [@[@"Aud", @"ioPl", @"aye", @"rIm", @"pl"] componentsJoinedByString:@""];
Ivar implDelegate = class_getInstanceVariable(NSClassFromString(implClassName), "_delegate");

// if the weak delegate of AVAudioPlayer is nil, you should set the assign delegate of AudioPlayerImpl to nil too.
if (!self.delegate) {
object_setIvar(impl, implDelegate, nil);
}

// retain self.delegate to keep it alive during the execution of the finishedPlaying: method
id __strong strongDelegate = self.delegate;

// call the original method finishedPlaying:
[self dm_finishedPlaying:success];

// this line doesn't make sense, just to avoid warning and optimization by the compiler
strongDelegate = nil;
}

@end

Verification

After shipping this fix, production verification showed that it did work.

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:Fixing an AVAudioPlayer Crash

Author:lingyun

Published:2021-05-10 13:34

Updated:2026-10-07 00:00

Original link:https://tsuijunxi.github.io/en/2021/05/10/fixing-an-avaudioplayer-crash/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.