我的应用程序播放在线流。
但是,当用户导航到下一个视图控制器时,音乐会停止。以下是播放声音的代码:
- (void)start
{
@synchronized (self)
{
if (state == AS_PAUSED)
{
[self pause];
}
else if (state == AS_INITIALIZED)
{
NSAssert([[NSThread currentThread] isEqual:[NSThread mainThread]],
@"Playback can only be started from the main thread.");
notificationCenter =
[[NSNotificationCenter defaultCenter] retain];
self.state = AS_STARTING_FILE_THREAD;
internalThread =
[[NSThread alloc]
initWithTarget:self
selector:@selector(startInternal)
object:nil];
[internalThread setName:@"InternalThread"];
[internalThread start];
}
}
}
我试过了:
dispatch_async(dispatch_get_main_queue(),
^{
[internalThread start];
});
但它不起作用。有没有人有这方面的经验?
答案 0 :(得分:1)
您必须保留对AS对象的引用。
在我的情况下,我把AS包装成单身。
@implementation MyClass
static AudioStreamer *sharedStreamer = nil;
+(AudioStreamer *)sharedStreamer{
return sharedStreamer;
}
-(void)play{
playing=YES;
}
-(void)stop{
playing=NO;
}
-(IBAction)playStop{
if (!self.playing)
{
[self createStreamer];
[[MyClass sharedStreamer] start];
}
else
{
[[MyClass sharedStreamer] stop];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
if([MyClass sharedStreamer]){
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(playbackStateChanged:)
name:ASStatusChangedNotification
object:[MyClass sharedStreamer]];
[self playbackStateChanged:nil];
}
}
//
// createStreamer
//
// Creates or recreates the AudioStreamer object.
//
- (void)createStreamer{
if ([MyClass sharedStreamer]){
return;
}
[self destroyStreamer];
NSString *escapedValue =
[(NSString *)CFURLCreateStringByAddingPercentEscapes(
nil,
(CFStringRef)@"http://url.com"],
NULL,
NULL,
kCFStringEncodingUTF8)
autorelease];
NSURL *url = [NSURL URLWithString:escapedValue];
sharedStreamer = [[AudioStreamer alloc] initWithURL:url];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(playbackStateChanged:)
name:ASStatusChangedNotification
object:[MyClass sharedStreamer]];
}
//
// playbackStateChanged:
//
// Invoked when the AudioStreamer
// reports that its playback status has changed.
//
- (void)playbackStateChanged:(NSNotification *)aNotification {
if ([[MyClass sharedStreamer] isWaiting]){
playing = YES ;
} else if ([[MyClass sharedStreamer] isPlaying]) {
playing = YES;
} else if ([[MyClass sharedStreamer] isIdle]) {
playing = NO;
[self destroyStreamer];
}
}
//
// destroyStreamer
//
// Removes the streamer, the UI update timer and the change notification
//
- (void)destroyStreamer{
if ([MyClass sharedStreamer]){
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:ASStatusChangedNotification
object:[MyClass sharedStreamer]];
[[MyClass sharedStreamer] stop];
[sharedStreamer release];
sharedStreamer = nil;
}
}