Files
Morgan Pretty 03020ad556 Merge remote-tracking branch 'upstream/dev' into feature/groups-rebuild
# Conflicts:
#	Scripts/LintLocalizableStrings.swift
#	Session.xcodeproj/project.pbxproj
#	Session/Calls/Call Management/SessionCall.swift
#	Session/Calls/Call Management/SessionCallManager.swift
#	Session/Calls/WebRTC/WebRTCSession+DataChannel.swift
#	Session/Conversations/ConversationVC+Interaction.swift
#	Session/Conversations/Message Cells/Content Views/OpenGroupInvitationView.swift
#	Session/Conversations/Message Cells/Content Views/QuoteView.swift
#	Session/Conversations/Message Cells/Content Views/SwiftUI/OpenGroupInvitationView_SwiftUI.swift
#	Session/Conversations/Message Cells/Content Views/SwiftUI/VoiceMessageView_SwiftUI.swift
#	Session/Conversations/Settings/ThreadSettingsViewModel.swift
#	Session/Database/Migrations/_001_ThemePreferences.swift
#	Session/Home/GlobalSearch/GlobalSearchViewController.swift
#	Session/Home/HomeViewModel.swift
#	Session/Home/Message Requests/MessageRequestsViewModel.swift
#	Session/Home/New Conversation/NewMessageScreen.swift
#	Session/Media Viewing & Editing/GIFs/GiphyAPI.swift
#	Session/Media Viewing & Editing/GIFs/GiphyDownloader.swift
#	Session/Media Viewing & Editing/PhotoLibrary.swift
#	Session/Meta/MainAppContext.swift
#	Session/Meta/SessionApp.swift
#	Session/Meta/Translations/remove_unused_strings.swift
#	Session/Notifications/PushRegistrationManager.swift
#	Session/Onboarding/Onboarding.swift
#	Session/Settings/HelpViewModel.swift
#	Session/Settings/SettingsViewModel.swift
#	Session/Settings/Views/VersionFooterView.swift
#	Session/Shared/FullConversationCell.swift
#	Session/Shared/SessionHostingViewController.swift
#	Session/Utilities/BackgroundPoller.swift
#	Session/Utilities/UIContextualAction+Utilities.swift
#	SessionMessagingKit/Configuration.swift
#	SessionMessagingKit/Database/Models/Attachment.swift
#	SessionMessagingKit/Database/Models/ClosedGroup.swift
#	SessionMessagingKit/Database/Models/Interaction.swift
#	SessionMessagingKit/Database/Models/RecipientState.swift
#	SessionMessagingKit/Database/Models/SessionThread.swift
#	SessionMessagingKit/Jobs/FailedMessageSendsJob.swift
#	SessionMessagingKit/LibSession/Config Handling/LibSession+Contacts.swift
#	SessionMessagingKit/LibSession/Config Handling/LibSession+UserGroups.swift
#	SessionMessagingKit/LibSession/Config Handling/LibSession+UserProfile.swift
#	SessionMessagingKit/LibSession/LibSession+SessionMessagingKit.swift
#	SessionMessagingKit/Messages/Message.swift
#	SessionMessagingKit/Messages/Visible Messages/VisibleMessage.swift
#	SessionMessagingKit/Sending & Receiving/Attachments/ThumbnailService.swift
#	SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+MessageRequests.swift
#	SessionMessagingKit/Sending & Receiving/Message Handling/MessageReceiver+VisibleMessages.swift
#	SessionMessagingKit/Sending & Receiving/Message Handling/MessageSender+LegacyClosedGroups.swift
#	SessionMessagingKit/Sending & Receiving/MessageReceiver.swift
#	SessionMessagingKit/Sending & Receiving/MessageSender.swift
#	SessionMessagingKit/Sending & Receiving/Notifications/Models/SubscribeRequest.swift
#	SessionMessagingKit/Sending & Receiving/Notifications/Models/UnsubscribeRequest.swift
#	SessionMessagingKit/Sending & Receiving/Notifications/PushNotificationAPI.swift
#	SessionMessagingKit/Sending & Receiving/Pollers/CurrentUserPoller.swift
#	SessionMessagingKit/Sending & Receiving/Pollers/OpenGroupPoller.swift
#	SessionMessagingKit/Utilities/OWSAudioPlayer.m
#	SessionMessagingKit/Utilities/Preferences.swift
#	SessionMessagingKit/Utilities/ProfileManager.swift
#	SessionMessagingKitTests/Jobs/MessageSendJobSpec.swift
#	SessionMessagingKitTests/Open Groups/OpenGroupManagerSpec.swift
#	SessionNotificationServiceExtension/NSENotificationPresenter.swift
#	SessionShareExtension/ShareNavController.swift
#	SessionSnodeKit/LibSession/LibSession+Networking.swift
#	SessionSnodeKit/Networking/SnodeAPI.swift
#	SessionSnodeKit/Types/ProxiedContentDownloader.swift
#	SessionUIKit/Components/ConfirmationModal.swift
#	SessionUtilitiesKit/Database/Models/Identity.swift
#	SessionUtilitiesKit/General/AppContext.swift
#	SessionUtilitiesKit/General/FileSystem.swift
#	SessionUtilitiesKit/General/NSTimer+Proxying.m
#	SessionUtilitiesKit/General/SNUserDefaults.swift
#	SessionUtilitiesKit/General/UIDevice+featureSupport.swift
#	SessionUtilitiesKit/Media/MediaUtils.swift
#	SignalUtilitiesKit/Media Viewing & Editing/Image Editing/ImageEditorCropViewController.swift
#	SignalUtilitiesKit/Media Viewing & Editing/MediaMessageView.swift
#	SignalUtilitiesKit/Media Viewing & Editing/OWSVideoPlayer.swift
#	SignalUtilitiesKit/Screen Lock/ScreenLockViewController.swift
2024-11-25 16:03:15 +11:00

234 lines
5.8 KiB
Objective-C

//
// Copyright (c) 2018 Open Whisper Systems. All rights reserved.
//
#import "OWSAudioPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import <SessionUtilitiesKit/SessionUtilitiesKit.h>
#import <SessionMessagingKit/SessionMessagingKit-Swift.h>
NS_ASSUME_NONNULL_BEGIN
// A no-op delegate implementation to be used when we don't need a delegate.
@interface OWSAudioPlayerDelegateStub : NSObject <OWSAudioPlayerDelegate>
@property (nonatomic) AudioPlaybackState audioPlaybackState;
@end
#pragma mark -
@implementation OWSAudioPlayerDelegateStub
- (void)setAudioProgress:(CGFloat)progress duration:(CGFloat)duration
{
// Do nothing
}
- (void)showInvalidAudioFileAlert
{
// Do nothing
}
- (void)audioPlayerDidFinishPlaying:(OWSAudioPlayer *)player successfully:(BOOL)flag
{
// Do nothing
}
@end
#pragma mark -
@interface OWSAudioPlayer () <AVAudioPlayerDelegate>
@property (nonatomic, readonly) NSURL *mediaUrl;
@property (nonatomic, nullable) AVAudioPlayer *audioPlayer;
@property (nonatomic, nullable) NSTimer *audioPlayerPoller;
@property (nonatomic, readonly) OWSAudioActivity *audioActivity;
@end
#pragma mark -
@implementation OWSAudioPlayer
- (instancetype)initWithMediaUrl:(NSURL *)mediaUrl
audioBehavior:(OWSAudioBehavior)audioBehavior
{
return [self initWithMediaUrl:mediaUrl audioBehavior:audioBehavior delegate:[OWSAudioPlayerDelegateStub new]];
}
- (instancetype)initWithMediaUrl:(NSURL *)mediaUrl
audioBehavior:(OWSAudioBehavior)audioBehavior
delegate:(nullable id<OWSAudioPlayerDelegate>)delegate
{
self = [super init];
if (!self) {
return self;
}
_mediaUrl = mediaUrl;
_delegate = delegate;
// stringlint:ignore_start
NSString *audioActivityDescription = [NSString stringWithFormat:@"%@ %@", @"OWSAudioPlayer", self.mediaUrl];
_audioActivity = [[OWSAudioActivity alloc] initWithAudioDescription:audioActivityDescription behavior:audioBehavior];
// stringlint:ignore_stop
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:NSNotification.sessionDidEnterBackground
object:nil];
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[DeviceSleepManager_objc removeBlockWithBlockObject:self];
[self stop];
}
#pragma mark - Dependencies
- (OWSAudioSession *)audioSession
{
return SMKEnvironment.shared.audioSession;
}
#pragma mark
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
[self stop];
}
#pragma mark - Methods
- (BOOL)isPlaying
{
return (self.delegate.audioPlaybackState == AudioPlaybackState_Playing);
}
- (void)play
{
// get current audio activity
[self playWithAudioActivity:self.audioActivity];
}
- (void)playWithAudioActivity:(OWSAudioActivity *)audioActivity
{
[self.audioPlayerPoller invalidate];
self.delegate.audioPlaybackState = AudioPlaybackState_Playing;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
if (!self.audioPlayer) {
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.mediaUrl error:&error];
self.audioPlayer.enableRate = YES;
if (error) {
[self stop];
if ([error.domain isEqualToString:NSOSStatusErrorDomain]
&& (error.code == kAudioFileInvalidFileError || error.code == kAudioFileStreamError_InvalidFile)) {
[self.delegate showInvalidAudioFileAlert];
}
return;
}
self.audioPlayer.delegate = self;
if (self.isLooping) {
self.audioPlayer.numberOfLoops = -1;
}
}
[self.audioPlayer play];
[self.audioPlayerPoller invalidate];
__weak OWSAudioPlayer *weakSelf = self;
self.audioPlayerPoller = [NSTimer weakScheduledTimerWithTimeInterval:.05f repeats:YES onFire:^(NSTimer * _Nonnull timer) {
[weakSelf audioPlayerUpdated:timer];
}];
// Prevent device from sleeping while playing audio.
[DeviceSleepManager_objc addBlockWithBlockObject:self];
}
- (void)setCurrentTime:(NSTimeInterval)currentTime
{
[self.audioPlayer setCurrentTime:currentTime];
}
- (float)getPlaybackRate
{
return self.audioPlayer.rate;
}
- (NSTimeInterval)duration
{
return [self.audioPlayer duration];
}
- (void)setPlaybackRate:(float)rate
{
[self.audioPlayer setRate:rate];
}
- (void)pause
{
self.delegate.audioPlaybackState = AudioPlaybackState_Paused;
[self.audioPlayer pause];
[self.audioPlayerPoller invalidate];
[self.delegate setAudioProgress:(CGFloat)[self.audioPlayer currentTime] duration:(CGFloat)[self.audioPlayer duration]];
[self endAudioActivities];
[DeviceSleepManager_objc removeBlockWithBlockObject:self];
}
- (void)stop
{
self.delegate.audioPlaybackState = AudioPlaybackState_Stopped;
[self.audioPlayer pause];
[self.audioPlayerPoller invalidate];
[self.delegate setAudioProgress:0 duration:0];
[self endAudioActivities];
[DeviceSleepManager_objc removeBlockWithBlockObject:self];
}
- (void)endAudioActivities
{
[self.audioSession endAudioActivity:self.audioActivity];
}
- (void)togglePlayState
{
if (self.isPlaying) {
[self pause];
} else {
[self playWithAudioActivity:self.audioActivity];
}
}
#pragma mark - Events
- (void)audioPlayerUpdated:(NSTimer *)timer
{
[self.delegate setAudioProgress:(CGFloat)[self.audioPlayer currentTime] duration:(CGFloat)[self.audioPlayer duration]];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self stop];
[self.delegate audioPlayerDidFinishPlaying:self successfully:flag];
}
@end
NS_ASSUME_NONNULL_END