I’m trying to replicate some of the functionality in Apple’s avTouch, but I can’t get AVAudioPlayer to play a track.
It logs Could not play (null). The (null) represents AVAudioplayer player.url. However, when I log player.url, it returns correctly. I have also tested the stream URL (it’s from soundcloud).
I have pretty much only made two changes from the sample code.
- I’m using an audio stream URL, rather than a file.
-
I had to add
__bridgein the following code (I don’t really know what it is for though)OSStatus result = AudioSessionInitialize(NULL, NULL, NULL, NULL); if (result) NSLog(@"Error initializing audio session! %@", result); [[AVAudioSession sharedInstance] setDelegate: self]; NSError *setCategoryError = nil; [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError]; if (setCategoryError) NSLog(@"Error setting category! %@", setCategoryError); result = AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, RouteChangeListener, (__bridge void *)self); if (result) NSLog(@"Could not add property listener! %@", result); void RouteChangeListener( void * inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void * inData) { SongsViewController* This = (__bridge SongsViewController*)inClientData; if (inID == kAudioSessionProperty_AudioRouteChange) { CFDictionaryRef routeDict = (CFDictionaryRef)inData; NSNumber* reasonValue = (__bridge NSNumber*)CFDictionaryGetValue(routeDict, CFSTR(kAudioSession_AudioRouteChangeKey_Reason)); int reason = [reasonValue intValue]; if (reason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) { [This pausePlaybackForPlayer:This.player]; } } }
Edit: I think this is occurring b/c AVAudioPlayer is not meant for network streams. Can I simply change AVAudioPlayer to AVPLayer? I have a feeling it’s not that easy.
AVAudioPlayer is not meant for network streams. Apple docs:
Apple recommends that you use this class for audio playback unless you are playing audio captured from a network stream or require very low I/O latency.