objective-c - 如何使用 NSSound 播放/停止播放歌曲?
问题描述
我正在使用NSSound
从我的 FTP 服务器播放歌曲。
我的问题:
第一首歌不会停止,这样第二首歌就会重叠。
在这里我粘贴完整的代码。这是当我单击一首歌曲时的行为NSTableView
-(void)tableViewSelectionDidChange:(NSNotification *)notification{
NSInteger row = [[notification object] selectedRow];
NSString *URL = [NSString stringWithFormat:@"ftp://user:pass@IP/Public/Music/%@",[TableContents objectAtIndex:row]];
NSSound *song = [[NSSound alloc]initWithContentsOfURL:[NSURL URLWithString:URL] byReference:NO];
NSLog(@"is playing before %hhd", song.isPlaying);
if(song.isPlaying){
[song stop];
NSLog(@"is playing IF if %hhd", song.isPlaying);
}else{
[song play];
NSLog(@"is playing ELSE %hhd", song.isPlaying);
}
}
输出:
当我点击第一首歌时:
2018-10-06 23:51:08.488690+0200 AIOMediaCenter[4294:492923] is playing before 0
2018-10-06 23:51:08.489099+0200 AIOMediaCenter[4294:492923] is playing ELSE 1
当我点击第二首歌时:
2018-10-06 23:51:12.022284+0200 AIOMediaCenter[4294:492923] is playing before 0
2018-10-06 23:51:12.022375+0200 AIOMediaCenter[4294:492923] is playing ELSE 1
解决方案
每次单击它时,都会创建一个新song
对象。song
当您创建一个新对象时,您需要在某处存储指向该对象的指针,然后检查 1)该对象是否存在,2)isPlaying
是否TRUE
为了停止它。这将需要您进行更多计划。这超出了问题的范围。
song
(分配后你也永远不会释放它,这会泄漏内存。)
推荐阅读
- python - 'object' 在 2d python 列表中不可下标
- postgresql - 从 pg_constraint 中删除重复的约束使数据库处于损坏状态
- r - 如果第 1 列具有特定值,如何计算第 2 列的平均值?R
- javascript - Raycaster 对象未定义 mouseover Three.js
- java - 在 android canvas 上画一个特殊的形状
- arrays - FormArray 无法在我的反应式表单上打印
- php - 从 SQL 表中存储变量以供以后使用 PHP
- python-3.x - uWSGI + Gevent 没有收到来自 Nginx 的请求
- python - 如何在运行单独的 tinter 代码时运行循环
- angular - Angular 可重用的 crud 组件