Skip to content

Commit

Permalink
fix: stops the background music on android, ios #40
Browse files Browse the repository at this point in the history
  • Loading branch information
Sitronik committed Oct 6, 2021
1 parent c465527 commit 868a4e1
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 58 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,9 +331,10 @@ getDuration(options: { assetId: string; }) => Promise<{ duration: number; }>

#### ConfigureOptions

| Prop | Type |
| ---------- | -------------------- |
| **`fade`** | <code>boolean</code> |
| Prop | Type | Description |
| ---------- | -------------------- | -------------------- |
| **`fade`** | <code>boolean</code> |
| **`focus`** | <code>boolean</code> | A bool indicating whether or not to disable mixed audio. By default - <code>false</code>


#### PreloadOptions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public class Constant {
public static final String ASSET_ID = "assetId";
public static final String ASSET_PATH = "assetPath";
public static final String OPT_FADE_MUSIC = "fade";
public static final String OPT_FOCUS_AUDIO = "focus";
public static final String VOLUME = "volume";
public static final String AUDIO_CHANNEL_NUM = "audioChannelNum";
public static final String LOOP = "loop";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import static com.getcapacitor.community.audio.Constant.ERROR_AUDIO_ID_MISSING;
import static com.getcapacitor.community.audio.Constant.LOOP;
import static com.getcapacitor.community.audio.Constant.OPT_FADE_MUSIC;
import static com.getcapacitor.community.audio.Constant.OPT_FOCUS_AUDIO;
import static com.getcapacitor.community.audio.Constant.VOLUME;

import android.Manifest;
Expand Down Expand Up @@ -47,22 +48,15 @@ public class NativeAudio
private static HashMap<String, AudioAsset> audioAssetList;
private static ArrayList<AudioAsset> resumeList;
private boolean fadeMusic = false;
private AudioManager audioManager;

@Override
public void load() {
super.load();

AudioManager audioManager = (AudioManager) getBridge()
this.audioManager = (AudioManager) getBridge()
.getActivity()
.getSystemService(Context.AUDIO_SERVICE);

if (audioManager != null) {
int result = audioManager.requestAudioFocus(
this,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN
);
}
}

@Override
Expand Down Expand Up @@ -128,6 +122,14 @@ public void configure(PluginCall call) {

if (call.hasOption(OPT_FADE_MUSIC)) this.fadeMusic =
call.getBoolean(OPT_FADE_MUSIC);

if (call.hasOption(OPT_FOCUS_AUDIO) && this.audioManager != null) {
this.audioManager.requestAudioFocus(
this,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN
);
}
}

@PluginMethod
Expand Down
3 changes: 2 additions & 1 deletion ios/Plugin/Constant.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@

public class Constant {
public static let FadeKey = "fade"
public static let FocusAudio = "focus"
public static let AssetPathKey = "assetPath"
public static let AssetIdKey = "assetId"
public static let Volume = "volume"
public static let Loop = "loop"

public static let ErrorAssetId = "Asset Id is missing"
public static let ErrorAssetPath = "Asset Path is missing"
public static let ErrorAssetNotFound = "Asset is not loaded"
Expand Down
97 changes: 52 additions & 45 deletions ios/Plugin/Plugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,60 +13,67 @@ enum MyError: Error {
*/
@objc(NativeAudio)
public class NativeAudio: CAPPlugin {

var audioList: [String : Any] = [:]
var fadeMusic = false

var session = AVAudioSession.sharedInstance()

public override func load() {
super.load()

self.fadeMusic = false

do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSession.Category.playback)
try session.setActive(false)
try self.session.setCategory(AVAudioSession.Category.ambient)
try self.session.setActive(false)
} catch {
print("Failed to ")
}
}

@objc func configure(_ call: CAPPluginCall) {
let fade: Bool = call.getBool(Constant.FadeKey) ?? false

let focus: Bool = call.getBool(Constant.FocusAudio) ?? false
if focus {
do {
try session.setCategory(AVAudioSession.Category.playback)
} catch {
print("Failed to ")
}
}
fadeMusic = fade
}

@objc func preload(_ call: CAPPluginCall) {
preloadAsset(call, isComplex: true)
}

@objc func play(_ call: CAPPluginCall) {
let audioId = call.getString(Constant.AssetIdKey) ?? ""
let time = call.getDouble("time") ?? 0
if audioId != "" {
let queue = DispatchQueue(label: "com.getcapacitor.community.audio.complex.queue", qos: .userInitiated)

queue.async {
if self.audioList.count > 0 {
let asset = self.audioList[audioId]

if asset != nil {
if asset is AudioAsset {
let audioAsset = asset as? AudioAsset

if self.fadeMusic {
audioAsset?.playWithFade(time: time)
} else {
audioAsset?.play(time: time)
}

call.success()
} else if (asset is Int32) {
let audioAsset = asset as? NSNumber ?? 0

AudioServicesPlaySystemSound(SystemSoundID(audioAsset.intValue ))

call.success()
} else {
call.error(Constant.ErrorAssetNotFound)
Expand All @@ -76,7 +83,7 @@ public class NativeAudio: CAPPlugin {
}
}
}

@objc private func getAudioAsset(_ call: CAPPluginCall) -> AudioAsset? {
let audioId = call.getString(Constant.AssetIdKey) ?? ""
if audioId == "" {
Expand All @@ -92,8 +99,8 @@ public class NativeAudio: CAPPlugin {
call.error(Constant.ErrorAssetNotFound + " - " + audioId)
return nil
}


@objc func getDuration(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
Expand All @@ -103,12 +110,12 @@ public class NativeAudio: CAPPlugin {
"duration": audioAsset.getDuration()
])
}

@objc func getCurrentTime(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
}

call.resolve([
"currentTime": audioAsset.getCurrentTime()
])
Expand All @@ -122,7 +129,7 @@ public class NativeAudio: CAPPlugin {
audioAsset.resume()
call.success()
}

@objc func pause(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
Expand All @@ -131,26 +138,26 @@ public class NativeAudio: CAPPlugin {
audioAsset.pause()
call.success()
}

@objc func stop(_ call: CAPPluginCall) {
let audioId = call.getString(Constant.AssetIdKey) ?? ""

do {
try stopAudio(audioId: audioId)
} catch {
call.error(Constant.ErrorAssetNotFound)
}
}

@objc func loop(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
}

audioAsset.loop()
call.success()
}

@objc func unload(_ call: CAPPluginCall) {
let audioId = call.getString(Constant.AssetIdKey) ?? ""
if self.audioList.count > 0 {
Expand All @@ -161,50 +168,50 @@ public class NativeAudio: CAPPlugin {
self.audioList[audioId] = nil
}
}

call.success()
}

@objc func setVolume(_ call: CAPPluginCall) {
guard let audioAsset: AudioAsset = self.getAudioAsset(call) else {
return
}

let volume = call.getFloat(Constant.Volume) ?? 1.0

audioAsset.setVolume(volume: volume as NSNumber)
call.success()
}

private func preloadAsset(_ call: CAPPluginCall, isComplex complex: Bool) {
let audioId = call.getString(Constant.AssetIdKey) ?? ""
let channels: NSNumber?
let volume: Float?
let delay: NSNumber?
let isUrl: Bool?

if audioId != "" {
let assetPath: String = call.getString(Constant.AssetPathKey) ?? ""

if (complex) {
volume = call.getFloat("volume") ?? 1.0
channels = NSNumber(value: call.getInt("channels") ?? 1)
delay = NSNumber(value: call.getInt("delay") ?? 1)
delay = NSNumber(value: call.getInt("delay") ?? 0)
isUrl = call.getBool("isUrl") ?? false
} else {
channels = 0
volume = 0
delay = 0
isUrl = false
}

if audioList.isEmpty {
audioList = [:]
}

let asset = audioList[audioId]
let queue = DispatchQueue(label: "com.getcapacitor.community.audio.simple.queue", qos: .userInitiated)

queue.async {
if asset == nil {
var basePath: String?
Expand All @@ -215,22 +222,22 @@ public class NativeAudio: CAPPlugin {
let url = URL(string: assetPath)
basePath = url!.path
}

if FileManager.default.fileExists(atPath: basePath ?? "") {
if !complex {
let pathUrl = URL(fileURLWithPath: basePath ?? "")
let soundFileUrl: CFURL = CFBridgingRetain(pathUrl) as! CFURL
var soundId = SystemSoundID()

AudioServicesCreateSystemSoundID(soundFileUrl, &soundId)
self.audioList[audioId] = NSNumber(value: Int32(soundId))

call.success()
} else {
let audioAsset: AudioAsset = AudioAsset(owner: self, withAssetId: audioId, withPath: basePath, withChannels: channels, withVolume: volume as NSNumber?, withFadeDelay: delay)

self.audioList[audioId] = audioAsset

call.success()
}
} else {
Expand All @@ -240,15 +247,15 @@ public class NativeAudio: CAPPlugin {
}
}
}

private func stopAudio(audioId: String) throws {
if self.audioList.count > 0 {
let asset = self.audioList[audioId]

if asset != nil {
if asset is AudioAsset {
let audioAsset = asset as? AudioAsset

if self.fadeMusic {
audioAsset?.playWithFade(time: audioAsset?.getCurrentTime() ?? 0)
} else {
Expand Down
1 change: 1 addition & 0 deletions src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export interface NativeAudio {

export interface ConfigureOptions {
fade?: boolean;
focus?: boolean;
}

export interface PreloadOptions {
Expand Down

0 comments on commit 868a4e1

Please sign in to comment.